图例未出现在ggplot中

时间:2020-11-02 05:31:19

标签: r ggplot2 legend

所以我很难让图例出现在图表中。我知道我正在使用两个数据集。而且我添加了aes()函数,但仍然无法正常工作。

shear_stress <-c(0.637,1.335,2.8,5.874,12.32,25.84,54.19,113.7,238.4,500)
five_glycerol <- data.frame(shear_rate,shear_stress)
five_glycerol

shear_rate2 <-c(6.492,33.67,60.42,102.8,129.4,156.4,182.7,209.8,236.1,263.2)
shear_stress2 <- c(0.637,1.335,2.8,5.874,12.32,25.84,54.19,113.7,238.4,500)
fifteen_glycerol <- data.frame(shear_rate2, shear_stress2)
fifteen_glycerol


p = ggplot() + geom_smooth(data = five_glycerol, aes(x = shear_rate, y = shear_stress), aes(color = "green"))+
  geom_smooth(data = fifteen_glycerol, aes(x = shear_rate2, y = shear_stress2), aes(color = "red"))+ xlab("Shear Rate")+ ylab("Shear Stress")
print(p)

1 个答案:

答案 0 :(得分:2)

您的语法不正确。您在一个aes()呼叫中有两个geom_*()呼叫。尝试以下

ggplot() + 
  geom_smooth(aes(x = shear_rate, y = shear_stress, color = "Five glycerol"), data = five_glycerol) +
  geom_smooth(aes(x = shear_rate2, y = shear_stress2, color = "Fifteen glycerol"), data = fifteen_glycerol) + 
  xlab("Shear Rate") + 
  ylab("Shear Stress")

enter image description here

接下来,您可以使用scale_colour_discrete(values = c('red', 'green'))或其他任何颜色来更改颜色。