【问题标题】:ggplot2 ggsave pdf solid lines around transparent boxesggplot2 ggsave pdf 透明框周围的实线
【发布时间】:2017-06-06 15:08:46
【问题描述】:

我想比较直方图中的不同峰值,所以我将其中两个放在一个 alpha=0.5 的图中。 RStudio 中的默认输出看起来不错,但是当我使用 pdf() 或 ggsave() 甚至 CairoPDF() 时,结果输出在框周围有实线。在我的情况下,这些实线有时在缩放 pdf 显示时看起来非常难看。我想禁用这些实线,或者至少让这些线的颜色/alpha 与填充相同。

最小代码示例:

library(ggplot2)

p1<-ggplot()+
  geom_histogram(data=diamonds[diamonds$cut == "Premium",],aes(x=depth,fill=cut),alpha=0.5)+
  geom_histogram(data=diamonds[diamonds$cut == "Ideal",],aes(x=depth,fill=cut),alpha=0.5)

ggsave("histoline.pdf",p1)

这是输出:

我尝试了各种方法来修改线型和尺寸,但直到现在都没有成功。

【问题讨论】:

  • 你试过size吗?
  • size=0 的结果相同,size=-1 和 size=NA 没有输出 =(
  • linetype="blank" 对我也不起作用
  • 嗯,也许这些条有点重叠?
  • 当我放大到 6400% 时,间隙变得可见

标签: r pdf ggplot2


【解决方案1】:

一种解决方法是手动计算直方图并使用 ggplot 仅显示相应的多边形。它看起来像我想要的,但当然那是一些额外的代码行,你会失去很多 ggplot 功能。注意: hist() 和 geom_hist() 对 bin 宽度的处理略有不同。

library(ggplot2)


hP <-hist(diamonds[diamonds$cut == "Premium",]$depth,breaks=seq(43,68,1))
hPd<-data.frame(breaks=c(hP$breaks[-1],hP$breaks),counts=c(hP$counts,hP$counts,hP$counts[1]))
hPd<-hPd[order(hPd$breaks),]

hI <- hist(diamonds[diamonds$cut == "Ideal",]$depth,breaks=seq(43,68,1))
hId<-data.frame(breaks=c(hI$breaks[-1],hI$breaks),counts=c(hI$counts,hI$counts,hI$counts[1]))
hId<-hId[order(hId$breaks),]

p1<-ggplot()+
  geom_polygon(data=hPd,aes(x=breaks,y=counts),fill="blue",alpha=0.5)+
  geom_polygon(data=hId,aes(x=breaks,y=counts),fill="red",alpha=0.5)
  #  this should yield the same binning behaviour as hist()
  #  geom_histogram(data=diamonds[diamonds$cut == "Premium",]
                  #,aes(x=depth),fill="green",binwidth=1,center=0.5,alpha=0.5)

print(p1)

ggsave("histoline.pdf",p1)

【讨论】:

  • 让我们称之为变通。看起来像我想要的,但是那里的方式不是很优雅
猜你喜欢
  • 2016-04-22
  • 2014-12-03
  • 1970-01-01
  • 1970-01-01
  • 2011-10-21
  • 1970-01-01
  • 2018-10-04
  • 2012-03-11
  • 1970-01-01
相关资源
最近更新 更多