【问题标题】:Legend disappears when moved inside of ggplot在 ggplot 内移动时图例消失
【发布时间】:2022-06-22 17:30:23
【问题描述】:

我正在制作一个图表,显示随着时间的推移几种动物的家园范围大小。图例自动填充到图的右侧,我可以使用+ theme(legend.position= "position") 成功地将它移动到图的上方、下方或左侧,但是当我尝试使用+ theme(legend.position= c(1, 250)) 在图中移动图例时,它消失了.

我的数据由列“id”(字符向量)、“wtd_area”(数字)和“study_year”(数字)组成。

data %>%
ggplot(aes(x= study_year, y= wtd_area, color= id, shape= id)) + 
  theme_js() + 
  geom_point(size= 3) + geom_line(aes(group=id), size= 1) + 
  ylim(0,160) + scale_color_manual(values= palette) + 
  labs(x= NULL, y= NULL, color= "Animal ID", shape= "Animal ID") +
  theme(legend.position= c(1,150))

我有:

1.) 确认自定义主题 theme_js() 不会因切换到通用主题而受到干扰。

2.) 将aes(color= id, shape= id)aes(color= id) 分别添加到geom_point()geom_line()

3.) 将show.legend= TRUE 添加到geom_point()geom_line()

4.) 将aesthetics= "color" 添加到scale_color_manual()

palette 是一个包含颜色十六进制代码的字符向量。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    该位置应在 0 到 1 的范围内,而不是对应于您的坐标区。 x,y 为 0,0(左下)到 1,1(右上)。这里我以ToothGrowth的样本数据为例。

    ToothGrowth$dose <- as.factor(ToothGrowth$dose)
    
    library(ggplot2)
    
    ggplot(ToothGrowth, aes(x=dose, y=len, fill=dose)) + 
      geom_boxplot() +
      theme(legend.position = c(0.8, 0.2))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-17
      • 1970-01-01
      • 2019-10-17
      • 1970-01-01
      • 2011-12-13
      • 2015-05-25
      • 1970-01-01
      相关资源
      最近更新 更多