Home > Mobile >  Legend disappears when moved inside of ggplot
Legend disappears when moved inside of ggplot

Time:06-16

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.

My data consists of columns "id" (a character vector), "wtd_area" (numeric), and "study_year" (numeric).

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.

2.) Added aes(color= id, shape= id) and aes(color= id) to geom_point() and geom_line() respectively.

3.) Added show.legend= TRUE to geom_point() and geom_line().

4.) Added aesthetics= "color" to scale_color_manual().

palette is a character vector containing color hex codes.

Thank you in advance.

CodePudding user response:

The position should be on a scale of 0 to 1, rather than corresponding to your axes. The x,y is 0,0 (bottom left) to 1,1 (top right). Here, I use the ToothGrowth sample data as an example.

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))

enter image description here

  • Related