简体   繁体   English

在 ggplot 内移动时图例消失

[英]Legend disappears when moved inside of ggplot

I am making a plot that shows the home range size of several animals over time.我正在制作一个图,显示随着时间的推移几种动物的家庭范围大小。 The legend automatically populates to the right of the plot, and I can successfully move it above, below, or to the left of the plot with + theme(legend.position= "position") , but when I try to move the legend within the plot using + theme(legend.position= c(1, 250)) it disappears.图例自动填充到图的右侧,我可以使用+ theme(legend.position= "position")成功地将它移动到图的上方、下方或左侧,但是当我尝试将图例移动到使用+ theme(legend.position= c(1, 250))的情节消失了。

My data consists of columns "id" (a character vector), "wtd_area" (numeric), and "study_year" (numeric).我的数据由列“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))

I have:我有:

1.) Confirmed that the custom theme theme_js() is not interfering by switching to a generic theme. 1.) 确认自定义主题theme_js()不会通过切换到通用主题来干扰。

2.) Added aes(color= id, shape= id) and aes(color= id) to geom_point() and geom_line() respectively. 2.) 分别为geom_point()geom_line() ) 添加了aes(color= id, shape= id)aes(color= id)

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

4.) Added aesthetics= "color" to scale_color_manual() . 4.) 在scale_color_manual()中添加了aesthetics= "color"

palette is a character vector containing color hex codes. palette是包含颜色十六进制代码的字符向量。

The position should be on a scale of 0 to 1, rather than corresponding to your axes.该位置应在 0 到 1 的范围内,而不是对应于您的轴。 The x,y is 0,0 (bottom left) to 1,1 (top right). x,y 为 0,0(左下)到 1,1(右上)。 Here, I use the ToothGrowth sample data as an example.在这里,我以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))

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM