在堆叠条形图上叠加点,并在空白背景上为点添加图例键

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

我需要一个堆叠条形图,显示

diamonds
的切割和清晰度,主要 y 轴(左侧)和次要 x 轴(右侧)的平均价格。如何包含点的图例项?所需的图应该有另一个点的键:只是白色背景上的黑点并显示为“平均价格”。

点的虚拟 df

library(dplyr)

price.avg <- diamonds %>%
   group_by(cut, color) %>%
   summarise(price = mean(price))

双 y 轴主图

library(ggplot2)

diamonds %>%
ggplot() +
geom_bar(aes(x = cut, fill = clarity)) +
facet_wrap(~ color, scale="free_y") +
ylab("Count") +
  xlab("Cut") + 
  geom_point(data = price.avg, aes(x = cut, y = price)) +
    scale_y_continuous(sec.axis = sec_axis(~. * 1, name = "price"))

使用

geom_point(data = price.avg, aes(x = cut, y = price), show.legend = TRUE)
在每个图例键中放一个点,这是我不想拥有的。

感谢您的光临。

r ggplot2 overlay stacked-bar-chart geom-point
1个回答
0
投票

您可以在

price.avg
数据框中包含一个具有相同值的虚拟变量,然后在虚拟变量上使用
aes(color)
,并设置
scale_color_manual
.

library(dplyr)
library(ggplot2)

price.avg <- diamonds %>%
  group_by(cut, color) %>%
  summarise(price = mean(price), dummy = "1")

diamonds %>%
  ggplot() +
  geom_bar(aes(x = cut, fill = clarity)) +
  facet_wrap(~ color, scale="free_y") +
  ylab("Count") +
  xlab("Cut") + 
  geom_point(data = price.avg, aes(x = cut, y = price, col = dummy)) +
  scale_y_continuous(sec.axis = sec_axis(~. * 1, name = "price")) +
  scale_color_manual(name = "", label = "Average price", values = "black")

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