图例中的 R Markdown 标签不正确

My Result

purple <- birth_data %>% filter(state_color =='purple' ) %>% group_by(year) %>% summarise(mean_age = mean(mother_age)) 
red <- birth_data %>% filter(state_color =='red' ) %>% group_by(year) %>% summarise(mean_age = mean(mother_age)) 
blue <- blue %>% mutate(state_color = 'blue')
purple <- purple %>% mutate(state_color  = 'purple')
red <- red %>% mutate(state_color = 'red')



graph <- ggplot() +  geom_line(data = blue,aes(x = year,y = mean_age,color = "Blue"),size =1.5)+
  geom_line(data = purple,color = "Purple"),size = 1.5)+
  geom_line(data = red,color = "Red"),size = 1.5) + labs(color='state_color')

graph

我正在尝试将 state_color 设置为与名称相同的颜色,因此图例中的蓝色应为蓝色。不幸的是,它不起作用?


此外,这不是问题的重点,但有没有更有效的方法来解决这个问题,而不是将它们分开然后重新融合在一起?

bingning128 回答:图例中的 R Markdown 标签不正确

尝试了解 {ggplot} 如何控制颜色,特别是 aesthetic mappings 是什么,parameters 是什么。

library(ggplot2)

df <- data.frame(x = 1:6,y = c(1,1,2,3,3),state_colour = c("red","red","blue","purple","purple"))

df
  x y state_colour
1 1 1          red
2 2 1          red
3 3 2         blue
4 4 2         blue
5 5 3       purple
6 6 3       purple

使用标准的 ggplot 调用:

ggplot(data = df) + 
   geom_line(aes(x = x,y = y,colour = state_colour))

你得到:

enter image description here

这是为什么?您正在将颜色美学分配给一个变量,该变量是具有不同值的字符向量/因子。像这样的“词”没有意义。您可以使用 A、B、C。{ggplot} 使用其 - 无可否认的 - 默认颜色序列。

如果您想像以前那样对数据框进行子集化,可以为该层指定颜色(即在 aes() 之外)

ggplot() + 
   geom_line(data = df %>% filter(state_colour == "blue"),aes(x = x,y = y),colour = "blue"    # colour is now a paramter and not an aesthetic mapping!
)

这产生:

setting colour parameter

本文链接:https://www.f2er.com/4541.html

大家都在问