R - ggplot 线条颜色(使用 geom_line)不会改变 [英] R - ggplot line color (using geom_line) doesn't change
问题描述
当使用 ggplot(geom_line) 在一个图上绘制 2 条线时,线的颜色与我设置的颜色不符.我想要黑色和蓝色的线条,但结果是红色和蓝色.我在没有(第一个代码)和(第二个)'scale_color_manual'的情况下尝试了它,还尝试了颜色插入,结果相同:
When ploting 2 lines on one plot with ggplot(geom_line) the color of the line doesn't compre to the color that I set. I want the lines black and blue, but the outcome is red and blue. I tried it without (first code) and with (second) 'scale_color_manual', also tried with colour insted of color, with the same result:
第一个代码:
ggplot(data=main_data) +
# black plot
geom_line(aes(x=vectors_growth_rate_with_predator,
y=disease_prevalnce_with_predator,
color = "black")) +
# blue plot
geom_line(aes(x=vectors_growth_rate_with_predator,
y=disease_prevalnce_without_predator,
color = "blue"))
第二个代码:
PrevVSGrowth =
ggplot(data=main_data) +
# black plot
geom_line(aes(x=vectors_growth_rate_with_predator,
y=disease_prevalnce_with_predator)) +
# blue plot
geom_line(aes(x=vectors_growth_rate_with_predator,
y=disease_prevalnce_without_predator))
PrevVSGrowth + scale_color_manual(values=c(disease_prevalnce_with_predator= 'black',
disease_prevalnce_without_predator = 'blue'))
推荐答案
你的第一个代码应该是
ggplot(data=main_data) +
# black plot
geom_line(aes(x=vectors_growth_rate_with_predator,
y=disease_prevalnce_with_predator),
color = "black") +
# blue plot
geom_line(aes(x=vectors_growth_rate_with_predator,
y=disease_prevalnce_without_predator),
color = "blue")
你需要把color
放在aes()
之外.
对于您的第二个代码,您需要从宽到长格式.您可以通过多种方式做到这一点,以下应该适合您.
For your second code you need to reshape your data from wide to long format. You can do this in many ways, the following should work for you.
library(tidyverse)
main_data <- main_data %>%
gather(key, value, c("disease_prevalnce_with_predator",
"disease_prevalnce_without_predator")
PrevVSGrowth <- ggplot(data=main_data) +
geom_line(aes(x=vectors_growth_rate_with_predator,
y=value,
col = key))
PrevVSGrowth +
scale_color_manual(values = c(disease_prevalnce_with_predator= 'black',
disease_prevalnce_without_predator = 'blue'))
在第一个图中,我们在每次调用 geom_line()
时设置一个固定值的审美.这将创建两个仅包含值black"的新变量;分别为蓝色"和蓝色".在 OP 的示例中,值黑色"是和蓝色"然后缩放为红色和浅蓝色并添加图例.
In the first plot we set an aesthetic to a fixed value, in each call to geom_line()
. This creates two new variables containing only the value "black" and "blue", respectively. In OP's example the values "black" and "blue" are then scaled to red and lightblue and a legend is added.
在第二个图中,我们映射颜色美学到一个变量(在这个例子中是key
).这通常是首选方式.
In the second plot we map the colour aesthetic to a variable (key
in this example). This is usually the preferred way.
这篇关于R - ggplot 线条颜色(使用 geom_line)不会改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!