简体   繁体   English

某一列的ggplot2条形图标签,用于按多列分组的数据

[英]ggplot2 bar chart labels for one column for data grouped by multiple columns

I have a bar chart with x axis labels grouped by 2 column values. 我有一个条形图,其中x轴标签按2列值分组。 In the plot I want to show one column ( method ) values as legend and mark the other ( variable ) as labels on the plot itself for an easy to read picture. 在绘图中,我想将一列( method )值显示为图例,并将另一列( variable )标记为绘图上的标签,以便于阅读。 However each label on graph is repeated due to the grouping by the other column. 但是,由于按另一列进行分组,因此重复了图形上的每个标签。 How can I have a single label for a unique value instead of repeating it.? 如何为唯一值使用单个标签,而不是重复该标签?

Sample data and current output is below. 示例数据和电流输出如下。

df <- data.table(w = rep(1:3, each = 3), 
        value = c(1.83,1.83,1.94,1.78,.95,1.09,3.14,3.14,3.14),
        method = seq(letters[1:3]),
        variable = c("fit","fit","fit","lwr","lwr","lwr","upr","upr","upr"))
ggplot(df,aes(x=w, y=value, color=factor(variable), fill=factor(method))) +
        geom_bar(stat="identity", position = "dodge") +
        geom_text(aes(label=paste(variable)), position = position_dodge(width =0.9),vjust=-.25) +
        theme_bw() +
        scale_y_log10(breaks=c(1,2,11,101,1001),labels=c(0,1,10,100,1000)) +
#       facet_wrap(~ppm) +
        annotation_logticks(sides = "lr")

在此处输入图片说明

I'm fond of saying ggplot2 is very good at plotting the data you give it . 我喜欢说ggplot2非常擅长绘制您提供的数据 The variable you are using as the label has the repetition that is being plotted: 您用作标签的变量具有绘制的重复项:

variable<-c("fit","fit","fit","lwr","lwr","lwr","upr","upr","upr")

If you don't want that repetition, create a variable without it for use as the label: 如果您不希望重复,则创建一个不带变量的变量用作标签:

 df$label = ifelse(df$method == "b", as.character(df$variable), NA)

Then use aes(label = label) in your geom_text() call. 然后在您的geom_text()调用中使用aes(label = label)

I would also recommend against using both fill and color mapped to different variables in a bar chart, but that's up to you. 我也建议不要在条形图中同时使用映射到不同变量的fillcolor ,但这取决于您。 At the very least, if you define the color mapping in the geom_text() layer instead of in the plot initialization the bars won't have the clashing color outline. 至少,如果您在geom_text()层中而不是在绘图初始化中定义颜色映射,则这些条将没有冲突的颜色轮廓。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM