Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

r - ggplot2 has two figure legends. How to remove the top one?

I have a figure:

library(ggplot2)
df1 <- data.frame(matrix(, nrow=4, ncol=5))
colnames(df1) <- c("Metabolite", "OR", "CI_low", "CI_high", "Method")
df1$Metabolite <- c("Isoleucine", "Leucine", "Isoleucine", "Leucine")
df1$OR <- c(0.75, 0.64, 0.88, 0.95)
df1$CI_low <- c(0.61, 0.48, 0.8, 0.85)
df1$CI_high <- c(0.89, 0.8, 0.96, 1.05)
df1$Method <- c("Metabolomic", "Metabolomic", "GRS", "GRS")

#define colours for dots and bars
dotCOLS = c("#a6d8f0","#f9b282")
barCOLS = c("#008fd5","#de6b35")


ggplot(df1, aes(x=Metabolite, y=OR, ymin=CI_low, ymax=CI_high,col=Method,fill=Method)) + 
  #specify position here
  geom_linerange(size=1,position=position_dodge(width = 0.5)) +
  geom_hline(yintercept=1, lty=2) +
  #specify position here too
  geom_point(size=3, shape=21, colour="white", stroke = 0.5,position=position_dodge(width = 0.5)) +
  scale_fill_manual(values=barCOLS)+
  scale_color_manual(values=dotCOLS)+
  scale_x_discrete(name="Metabolite") +
  scale_y_continuous(name="Odds ratio (95% CI)", limits = c(0.4, 2)) +
  coord_flip() +
  guides(fill = guide_legend(reverse = TRUE)) +
  theme_minimal()

As you can see, there are two legends. The top one is the incorrect way round and I wish to remove it. How would I do this? Alternatively, could I remove the bottom one and flip the top one round? Essentially, I just want one legend the correct way round.

question from:https://stackoverflow.com/questions/65625849/ggplot2-has-two-figure-legends-how-to-remove-the-top-one

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can specify show.legend = FALSE in geom_linerange :

library(ggplot2)

ggplot(df1, aes(x=Metabolite, y=OR, ymin=CI_low, ymax=CI_high,col=Method,fill=Method)) + 
  #specify position here
  geom_linerange(size=1,position=position_dodge(width = 0.5), show.legend = FALSE) +
  geom_hline(yintercept=1, lty=2) +
  #specify position here too
  geom_point(size=3, shape=21, colour="white", stroke = 0.5,position=position_dodge(width = 0.5)) +
  scale_fill_manual(values=barCOLS)+
  scale_color_manual(values=dotCOLS)+
  scale_x_discrete(name="Metabolite") +
  scale_y_continuous(name="Odds ratio (95% CI)", limits = c(0.4, 2)) +
  coord_flip() +
  theme_minimal()

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...