【问题标题】:Adding a single legend for two horizontal lines in ggplot在ggplot中为两条水平线添加单个图例
【发布时间】:2019-12-06 15:48:07
【问题描述】:

我对 ggplot2 的经验很少。我正在尝试使用以下代码绘制覆盖概率和队列大小:

library("reshape2")
library("ggplot2")
library(latex2exp)
CP1 <-c(0.953,0.942,0.947,0.958)
CP2 <- c(0.937,0.952,0.955,0.957)
cohort <- c(500,1000,5000,10000)
mdata <- data.frame(rate1=CP1,rate2=CP2,cohort.size=cohort)

mydata <- melt(mdata,id='cohort.size',value.name="CP")
ggplot(mydata , aes(x=cohort.size, y=CP)) +
  geom_line(size=1,aes(colour=variable)) +
  geom_point( size=4, shape=0)+ coord_cartesian(ylim = c(0,1)) +
  scale_x_continuous(breaks=c(500,1000,5000,10000))+
  scale_color_discrete(labels = unname(TeX(c(" $\\r_1$", "$\\r_2$")))) +
  geom_hline(yintercept =c(0.936,0.964) ,linetype="dashed") + 

  theme(legend.title = element_blank(), axis.title.x = element_text(color="#993333", size=14, face="bold"), 
        axis.title.y = element_text(color="#993333", size=14, face="bold"),
        plot.title = element_text(color="#993333", size=14, face="bold"),
        legend.position = c(.85, .85),
        legend.justification = c("right", "top"),
        legend.box.just = "right",
        legend.margin = margin(6, 6, 6, 6),legend.text=element_text(size=20)) + xlab("Cohort Size") + ylab("Coverage Proability")+

  annotate("text",
           x = 8700,
           y = 0.68, 
           label =expression(bold(paste("MN=57% \n AB=38% \n XYZ=5%" ))),parse = TRUE,size=5)

我有三个问题: 1. 运行代码时,收到警告;我该如何解决。 2. 有两条水平的 黑色 虚线,我只想用一个图例来代表“95% CL”。 3. 感觉代码太多了,有没有更简单的方法,只用ggplot2来写。

谢谢!!

【问题讨论】:

  • 关于你的问题1,你能提供“错误”吗?
  • 不要将rm(list = ls()) 作为您问题的一部分发布,除非它对理解您的问题至关重要。没有人想复制您的代码并意外运行该行,从而清除他们可能正在处理的所有其他内容。
  • @dc37这是警告而不是错误;我已经编辑了这个问题。警告是:在 is.na(x) 中:is.na() 应用于“表达式”类型的非(列表或向量)。
  • @Gregor,是的,你是对的。我很抱歉。
  • 不值得回答,但有几个想法可以减少代码:(a) 您希望两个轴标题的格式相同,因此axis.title = element_text(color="#993333", size=14, face="bold") 可以同时使用,不必指定axis.title.xaxis.title.y 分别。 (b) 您没有情节标题,因此您可以删除theme 中的plot.title 行。 (c) 我喜欢labs 标签接口,labs(x = "Cohort Size", y = "Coverage Proability") 而不是xlab(...) + ylab(...)。您还可以在同一个调用中指定图例标题 (color = "...") 和绘图标题 (title = "...")`。

标签: r ggplot2 plot simulation montecarlo


【解决方案1】:

我无法安装latex2exp。如果没有这个包,你可以试试这个,我认为所有三个问题都解决了:

ggplot(mydata , aes(x=cohort.size, y=CP)) + 
  geom_line(size=1,aes(colour=variable)) +
  geom_point( size=4, shape=0)+ 
  geom_hline(data = data.frame(yintercept =c(0.936,0.964)),
             aes(yintercept =yintercept, linetype ='95% CL')) +
  scale_linetype_manual("", values = 2) +
  ylim(0,1) +
  annotate("text",
           x = 8700,
           y = 0.68, 
           label = paste("MN=57%\n AB=38%\n XYZ=5%" ),
           size=5, fontface =2)

【讨论】:

  • 当我使用注释时出现警告,我不知道如何解决。它不需要安装latex2exp。
  • 非常感谢。问题解决了。只是一个简单的问题:当我保存并查看绘图的 pdf 时,绘图内的三个文本会更改位置。有没有办法避免这种情况?
  • 你使用ggsave("myplot.pdf")吗?
猜你喜欢
  • 1970-01-01
  • 2016-03-25
  • 1970-01-01
  • 2021-12-15
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多