首页 文章

ggplot2条形图标签和颜色

提问于
浏览
0

我在使用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

For labels

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

(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

For colours

我想在这里修改标准蓝色和红色的颜色 . 当我添加一个带有四种颜色的调色板时,每个条形获得一个单独的颜色
(chart example 2)
,而不是一个用于'spring',一个用于'winter' . 你会发现这样做也会弄乱所有标签和图例 .

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

错误:美学必须是长度1或与数据(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

    要修复文本躲避,请删除 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()
    

相关问题