在 ggplot2 中设置具有不同叠加图的组中的形状类型

问题描述 投票:0回答:1

我希望在按组编码时微调两个叠加图中的 ggplot2 形状类型。这可能吗?我创建了一个带状图,其中包含用于平均观察的点,针对播种率的两个不同因素使用两种不同的形状进行编码,针对不同的肥料价格情景使用三种不同的颜色进行编码。我包括了用于计算这些平均值的值的抖动观察值,也由为平均值点列出的相同颜色和形状组编码。我包括了显示每个平均值的标准误差的行。
为了提高可视化效果,我希望抖动观察是开放的形状,而方法是封闭的形状。

library(ggplot2)
p<-ggplot()+  geom_jitter(data=econ4,position=position_jitter(0.2),aes(x=location,y=profit,shape=seeding.rate,colour=urea.cost.USD,alpha=0.05))+theme_bw()+geom_hline(yintercept=0)+labs(y = "profit per ha (USD)")
p<-p+geom_point(data=econ4,aes(x=location,y=mean.profit,colour=urea.cost.USD,shape=seeding.rate))
p<-p+geom_linerange(data=econ4,aes(x=location,y=mean.profit,ymin=mean.profit-se.profit,ymax=mean.profit+se.profit,colour=urea.cost.USD)) 
#p<-p+scale_shape_manual(values=1:2)
p<-p+scale_colour_manual(values=c("#0072B2","#009E73", "#CC79A7"))
p<-p + coord_flip()
p<-p+scale_shape_manual(values=1:2) #this changes all shapes to open.  I would like this to apply only to the geom_jitter.

plot

r ggplot2 overlay shapes group
1个回答
0
投票

因为你想要不同的形状用于抖动和平均点映射

seeding.rate
shape
上是不够的。相反,您必须“重新编码”
seeding.rate
以区分抖动点和平均点并获得四种不同的形状。为此,您可以映射例如
paste0(seeding.rate, ".jitter")
shape
中的
geom_jitter
aes 和
paste0(seeding.rate, ".mean")
shape
中的
geom_point
aes 上。因此,我们有四个不同的类别,我们可以将您想要的四种不同形状分配给它们。

此外,我稍微重构了您的代码,而不是手动计算

mean
se
我使用
stat="summary"
来动态计算统计数据。

使用一些虚假的随机示例数据:

library(ggplot2)

set.seed(123)

econ4 <- data.frame(
  location = sample(LETTERS[1:5], 100, replace = TRUE),
  urea.cost.USD = sample(c("300", "550", "1000"), 100, replace = TRUE),
  seeding.rate = sample(c("Mirsky", "Poffenbarger"), 100, replace = TRUE),
  profit = rlnorm(100, 4) - 100
)

ggplot(econ4, aes(profit, location, colour = urea.cost.USD)) +
  geom_vline(xintercept = 0) +
  geom_jitter(
    position = position_jitter(0.2),
    aes(shape = paste0(seeding.rate, ".jitter")), alpha = .8,
    size = 2
  ) +
  geom_point(aes(shape = paste0(seeding.rate, ".mean")),
    stat = "summary", fun = mean, size = 2
  ) +
  geom_linerange(stat = "summary", fun.data = "mean_se") +
  scale_colour_manual(
    values = c("#0072B2", "#009E73", "#CC79A7")
  ) +
  scale_shape_manual(
    values = c(Mirsky.jitter = 16, Mirsky.mean = 21, Poffenbarger.jitter = 17, Poffenbarger.mean = 24),
    breaks = c("Mirsky.jitter", "Poffenbarger.jitter"),
    labels = c("Minsky", "Poffenbarger")
  ) +
  theme_bw() +
  labs(x = "profit per ha (USD)", shape = "seeding rate")

© www.soinside.com 2019 - 2024. All rights reserved.