[英]How to add legend to a combined line+box graph in ggplot2()
我有一个带有以下信息的 dataframe
但是我使用了下面的代码 plot 它(绘制的图表显示在评论后面),但不知道如何为这个组合(线和条)plot 添加图例。
#plot with ggplot2
ggplot(data) +
geom_col(aes(x=cluster_number, y=2*reduction_in_withincluster_variation), fill="grey", colour="black")+
geom_line(aes(x=cluster_number, y=within_cluster_variation), size=1)+
geom_point(aes(x=cluster_number, y=within_cluster_variation), pch =16)+
scale_x_continuous(breaks=seq(1, 16, 1)) +
labs(y = "Within-cluster variation", x = "Number of clusters")+
scale_y_continuous(breaks=seq(0, 0.14, 0.02), sec.axis = sec_axis(~./2, breaks=seq(0, 0.07, 0.01), name = "Reduction in within-cluster variation"))+
theme_classic(base_size = 13)
任何建议都会非常有帮助
谢谢!
plot 目前看起来像这样,我想为图表右侧的线和条添加一个图例。
要为给定的几何图形显示图例,您需要分配将在aes()
内的图例中表示的内容。 通常,这将应用于数据中的列,并根据该数据中每个观察值的值创建图例键条目并分配 colors。 但是,您也可以在aes()
中将字符串分配给诸如fill=
或color=
或linetype=
之类的美学。 这将产生为该特定几何创建图例键条目并将该美学条目添加到具有该名称的图例的效果。
我们可以将此方法应用于 OP 的示例。 他们没有共享数据,但这里有一个模拟 OP 显示的数据的示例(没有辅助 y 轴的东西等):
library(ggplot2)
data <- data.frame(
cluster_number = 1:16,
points_and_lines = c(0.14, 0.077, 0.052, 0.045, 0.038, 0.035, 0.033, 0.032, 0.032, 0.031, 0.029, 0.028, 0.027, 0.025, 0.024, 0.022),
bar_heights = c(0.12, 0.04, 0.02, 0.018, 0.012, 0.01, 0.008, 0.007, 0.007, 0.006, 0.004, 0.004, 0.004, 0.003, 0.002, 0.001)
)
p <- ggplot(data) +
geom_col(aes(x=cluster_number, y=bar_heights), fill="grey", colour="black")+
geom_line(aes(x=cluster_number, y=points_and_lines), size=1)+
geom_point(aes(x=cluster_number, y=points_and_lines), pch =16)+
scale_x_continuous(breaks=seq(1, 16, 1)) +
labs(y = "Within-cluster variation", x = "Number of clusters")+
theme_classic(base_size = 13)
p
这是上述策略的应用。 在这种情况下,我想对列使用fill=
,而对线和点使用color=
。 这将具有组合线的图例键中的外观+“线和点”的点并为列显示灰色框的净效果。 如果您只想要“线和点”的图例中的线或点条目,则可以仅将一个或另一个放入aes()
。
请注意,我们不仅需要在aes()
中为几何图形添加fill
和color
,而且还需要:(1)使图例标题为NULL
以避免出现图例标题(除非您想要它),以及(2)定义实际的 colors,否则, ggplot2
将 map 将它们设置为默认色调比例。
ggplot(data) +
geom_col(aes(x=cluster_number, y=bar_heights, fill="bars"), colour="black")+
geom_line(aes(x=cluster_number, y=points_and_lines), size=1)+
geom_point(aes(x=cluster_number, y=points_and_lines, color="lines and points"), pch =16)+
scale_x_continuous(breaks=seq(1, 16, 1)) +
labs(y = "Within-cluster variation", x = "Number of clusters", color=NULL, fill=NULL)+
scale_fill_manual(values="grey") +
scale_color_manual(values="black") +
theme_classic(base_size = 13) +
theme(legend.position="top")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.