ggplot2:如何在图例中同时展示两列数据信息?
解决方案
可以直接在ggplot的填充刻度配置中自定义图例标签,无需提前合并数据列,代码如下:
df <- data.frame(product = c("a", "b", "c", "d"), count = c(3, 4, 6, 7), name = c("ball", "pen", "notebook", "pencil")) ggplot(df, aes(x = "", y = count, fill = product)) + geom_bar(stat = "identity", width = 1) + coord_polar("y", start = 0) + scale_fill_discrete(labels = paste(df$product, df$name, sep = " - "))
说明
这种方法直接在绘图的刻度配置层生成组合标签,不需要修改原始数据框,既保留了数据的原始结构,又实现了图例同时展示两列信息的需求,比提前合并列更贴合ggplot的分层设计逻辑,简洁且优雅。
内容的提问来源于stack exchange,提问作者Honorato
相关产品推荐
相关产品推荐

