ggplot2条形图标签和颜色

时间:2017-12-11 16:00:53

标签: r ggplot2 bar-chart

我在使用geom_text向条形图添加标签和颜色时遇到问题。

这是数据的一个例子:Data

Season   Answer   n     freq         
Spring   Yes      103    0.77                    
Spring   No       30     0.23   
Winter   Yes      75     0.85
Winter   No       13     0.15                

对于标签

标签聚集在一起,而不是每个栏末端有一个数字。

(chart example)

ggplot(data = a, aes(x = Answer, y = freq)) + 
    geom_bar(aes(fill = season),stat = "identity", position = "dodge") +
    theme_minimal() + 
    scale_y_continuous(labels = scales::percent, limits = c(0, 1)) +
    geom_text(aes(label = freq, group = Answer),
              position=position_dodge(width = 0.5), vjust = -1.5) +
    ggtitle(label = "x") +
    labs (x = "%") +
    coord_flip()

我希望每个栏的末尾都有一个比例,而不是它们相互重叠。

我还希望比例显示为* 100。所以77.0%,而不是0.77

颜色

我想在这里修改标准蓝色和红色的颜色。当我添加一个有四种颜色的调色板时,每个条形都会得到一个单独的颜色(chart example 2),而不是一个用于“春天”的颜色。和一个冬天的#39;你会发现这样做也会弄乱所有标签和图例。

如果我使用两种颜色的调色板,我会得到这个:

Error: Aesthetics must be either length 1 or the same as the data (4): fill, x, y
ggplot(data = a, aes(x = Answer, y = freq)) + 
    geom_bar(aes(fill = "palette"),stat = "identity", position = "dodge") +
    theme_minimal() + 
    scale_y_continuous(labels=scales::percent,limits= c(0, 1))+
    geom_text(aes(label = freq, group = Answer),
              position = position_dodge(width = 0.5),
              vjust = -1.5) +
    ggtitle(label = "x") +
    labs (x = "%") +
    coord_flip()

1 个答案:

答案 0 :(得分:0)

要修复文字躲避,请放弃group美学并调整躲闪量。要设置填充调色板,请添加scale_fill_*来电,例如

library(ggplot2)

a <- data.frame(Season = c("Spring", "Spring", "Winter", "Winter"), 
                Answer = c("Yes", "No", "Yes", "No"), 
                n = c(103L, 30L, 75L, 13L), 
                freq = c(0.77, 0.23, 0.85, 0.15), stringsAsFactors = FALSE)

ggplot(data = a, aes(x = Answer, y = freq, fill = Season, label = scales::percent(freq))) + 
    geom_col(position = "dodge") +
    geom_text(position = position_dodge(width = .9)) +
    scale_y_continuous(labels = scales::percent, limits = c(0, 1)) +
    scale_fill_brewer(type = 'qual') + 
    theme_minimal() + 
    labs(title = "x", x = "%") +
    coord_flip()