首页 > 解决方案 > 在 R 中,如何使用 ggplot2 绘制具有 2 个分类值的三个不同值?

问题描述

我有一个原始数据集。

  gender neg_sentiment neu_sentiment pos_sentiment
  <fct>          <int>         <int>         <int>
 1  F            24216         10070         14734
 2  M            372863        162281        239366

我想像下图一样绘制这个数据集。

在此处输入图像描述

你能帮我做这个吗?

dput 如下所示:

structure(list(gender = structure(1:2, .Label = c("F", "M"), class = "factor"), 
neg_sentiment = c(24216L, 372863L), neu_sentiment = c(10070L, 
162281L), pos_sentiment = c(14734L, 239366L)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -2L))

标签: rggplot2

解决方案


您可以从宽到长重塑,然后使用 (gg) 绘图facet_wrap

library(tidyverse)
df %>%
    pivot_longer(-gender) %>%
    ggplot(aes(name, value, fill = name)) +
    geom_col() +
    facet_wrap(~ gender)

在此处输入图像描述


或者经过更多的微调/抛光

df %>%
    pivot_longer(-gender) %>%
    mutate(name = factor(
        name,
        levels = c("pos_sentiment", "neu_sentiment", "neg_sentiment"),
        labels = c("positive", "neutral", "negative"))) %>%
    ggplot(aes(name, value, fill = name)) +
    geom_col(show.legend = FALSE) +
    facet_wrap(~ gender, strip.position = "bottom") +
    labs(x = "") +
    scale_fill_manual(
        values = c("positive" = "darkblue", "neutral" = "blue", "negative" = "darkred")) +
    theme_minimal()

在此处输入图像描述


样本数据

df <- structure(list(gender = structure(1:2, .Label = c("F", "M"), class = "factor"),
neg_sentiment = c(24216L, 372863L), neu_sentiment = c(10070L,
162281L), pos_sentiment = c(14734L, 239366L)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -2L))

推荐阅读