【问题标题】:Stack multiple columns of df in bar/col plot在 bar/col 图中堆叠多列 df
【发布时间】:2020-11-09 17:07:23
【问题描述】:

我有以下 df

df <- data.frame(genre = c("Thriller", "Horror", "Action"), europe = c(30, 35, 50), asia = c(20, 15, 25), america = c(50, 50, 25))

     genre europe asia america
1 Thriller     30   20      50
2   Horror     35   15      50
3   Action     50   25      25

我想要剧情

有人有什么建议吗?在此先感谢:D

【问题讨论】:

    标签: r dataframe ggplot2


    【解决方案1】:

    使用pivot_longer 重塑您的数据:

    library(ggplot2)
    
    ggplot(tidyr::pivot_longer(df, -1), aes(genre, value, fill = name)) +
      geom_col(color = "gray20") +
      geom_text(aes(label = paste(value, "%")), fontface = "bold", size = 5,
                position = position_stack(vjust = 0.5)) +
      scale_fill_manual(values = c("#1ca4fc", "#fcad2a", "#595959"), 
                        name = "Continent") +
      theme(text = element_text(face = "bold", size = 18))
    

    【讨论】:

      【解决方案2】:

      这应该可行,您可以根据需要进一步更改颜色/排序。

      library(reshape2)
      df_melt = melt(df, id.vars = "genre")
      
      ggplot(df_melt, aes(x = genre, y = value, fill = variable)) +
        geom_bar(position = "stack", stat = "identity") +
        geom_text(aes(label = paste0(value, "%")), position = position_stack(vjust = 0.5))
      
      

      已编辑以包含标签。

      【讨论】:

        猜你喜欢
        • 2021-02-24
        • 2014-02-13
        • 2020-06-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-01
        相关资源
        最近更新 更多