我需要一个堆叠条形图,显示
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)
在每个图例键中放一个点,这是我不想拥有的。
感谢您的光临。
您可以在
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")