R

时间:2016-05-08 03:41:39

标签: r bar-chart

在此数据框中,Liked_byDisliked_by已按百分比转换。我尝试了多种方式,例如ggplot2,以获得类似于此示例的输出:enter image description here

在我的情况下,标记行将为name 1, ... , name 5,而条形图将为百分比中的supportoppose。数据框如下:

    df <- data.frame(Liked_by = c(0,0,1,9,2), Disliked_by = c(1,0,0,7,3), Recipient_Number = c(4,5,9,2,3), Name_Users = c("name 1", "name 2", "name 3", "name 4", "name 5" ), stringsAsFactors = FALSE) 

df$Recipient_Number <- df$Recipient_Number + 1 

df$support <- round((df$Liked_by/df$Recipient_Number)*100) # Liked_by rounded up
    # with percentage to call support 

df$oppose <- round((df$Disliked_by/df$Recipient_Number)*100)

# users <- c("Support", "Oppose")
# df1 <- data.matrix(df[ ,5:6])
# barplot(df1, main="Support vs Oppose", ylab = "in percentage [%]", cex.lab = 1.5, cex.main = 1.4, beside=TRUE, col=rainbow(10))
# barplot(df1,main = "Overall support-oppose", names.arg = users, xlab = "users", ylab = "support vs oppose", col = rainbow(20))

1 个答案:

答案 0 :(得分:2)

您需要重新排列数据,以满足您的绘图需求。在这种情况下,您需要将supportoppose融合到一列中,以便按照它们对条形填充进行分组。如果你想添加标签,你还需要弄清楚它们的绘制高度,这需要一点点思考。

最终,您可以使用默认的条形位置绘制,"stack"geom_bar,也可以将其更改为"fill",从底部到顶部缩放所有内容,例如您的示例张贴在上面。代码类似:

position = "stack"

library(tidyr)
library(dplyr)
library(ggplot2)

              # melt support and oppose columns together
df2 <- df %>% gather(var, value, support, oppose) %>% 
    group_by(Name_Users) %>% 
    # add label_height column at half of support and support + half of oppose
    mutate(label_height = ifelse(var == 'support', 
                                 value / 2, 
                                 sum(value) - value / 2))


ggplot(df2, aes(x = Name_Users, y = value, fill = var)) + 
    geom_bar(stat = 'identity') +    # plot bars to height of value column
    geom_text(aes(y = label_height, label = paste0(value, '%')))    # add labels

stacked barplot

position = "fill"

              # melt support and oppose columns together
df3 <- df %>% gather(var, value, support, oppose) %>% 
    group_by(Name_Users) %>% 
    # add label_height column like before, but scaled by dividing by the sum of each group
    mutate(label_height = ifelse(var == 'support', 
                                 value / 2, 
                                 sum(value) - value / 2) / sum(value))

ggplot(df3, aes(x = Name_Users, y = value, fill = var)) + 
    geom_bar(stat = 'identity', position = 'fill') +    # scale bars from 0-1
    geom_text(aes(y = label_height, label = paste0(value, '%')))    # add labels

filled barplot

显然,两个地块都没有生产就绪,两者都可以使用一些抛光,但你需要的核心功能就在这里。