如何在R中向该图表添加图例

w9apscun  于 2023-02-01  发布在  其他
关注(0)|答案(1)|浏览(171)

我从两个不同的表做了一个图表,红色是用户,蓝色是非用户。我如何创建一个图例。

structure(list(Attribute = c("Nscore", "Escore", "Oscore", "Ascore", 
"Cscore", "Impulsivity", "SS"), Mean = c(0.519519745762712, -0.224147033898305, 
0.345051694915254, -0.542761016949153, -0.432290169491526, 0.573723898305084, 
0.625454406779661), lower_bound = c(0.345515567755788, -0.421929253136834, 
0.173007836159723, -0.743825778750619, -0.620318735695037, 0.417301607369938, 
0.461852381381636), upper_bound = c(0.693523923769636, -0.0263648146597761, 
0.517095553670785, -0.341696255147686, -0.244261603288014, 0.730146189240231, 
0.789056432177685)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-7L))
structure(list(Attribute = c("Nscore", "Escore", "Oscore", "Ascore", 
"Cscore", "Impulsivity", "SS"), Mean = c(-0.0346437351443125, 
0.014794833050368, -0.0236125863044712, 0.0359841765704582, 0.0284564233163561, 
-0.0306152461799648, -0.0452792359932086), lower_bound = c(-0.0809079532901976, 
-0.0313902162687121, -0.0700665170072849, -0.00972637107557454, 
-0.0176800056429342, -0.0748829267378616, -0.089769617527101), 
    upper_bound = c(0.0116204830015727, 0.0609798823694481, 0.0228413443983426, 
    0.0816947242164909, 0.0745928522756465, 0.0136524343779321, 
    -0.000788854459316299)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -7L))
ggplot(UserCI, aes(Attribute, Mean)) + 
    geom_point() + geom_errorbar(aes(ymin = lower_bound, ymax = upper_bound), colour="red") +
    geom_point(data = NonUserCI, aes(Attribute, Mean)) + 
    geom_errorbar(aes(ymin =NonUserCI$lower_bound, ymax = NonUserCI$upper_bound), colour = "blue")
pqwbnv8z

pqwbnv8z1#

如果你想得到一个图例,然后Map在美学上,即Map在aes()内的color aes上,并通过scale_color_manual设置你想要的颜色:

library(ggplot2)

ggplot(UserCI, aes(Attribute, Mean)) +
  geom_point() +
  geom_errorbar(aes(ymin = lower_bound, ymax = upper_bound, color = "user")) +
  geom_point(data = NonUserCI, aes(Attribute, Mean)) +
  geom_errorbar(data = NonUserCI, aes(ymin = lower_bound, ymax = upper_bound, color = "nonuser")) +
  scale_color_manual(
    values = c("user" = "red", "nonuser" = "blue"),
    labels = c("user" = "User", "nonuser" = "Non-User")
  )

相关问题