首页 > 解决方案 > 使用 ggplot 和手动数据框一行 5 列创建条形图

问题描述

在此处输入图像描述

这是我的数据框。我找不到使用 ggplot 构造条形图的方法,其中列名和 x 作为指示的值。

标签: rdataframeggplot2data-visualizationdata-wrangling

解决方案


如评论中所述,发布代码/数据/错误的图像是不好的做法。我只复制了数据框的前两个条目。一般来说,对于 ggplot(和整个 tidyverse)观察应该在行而不是列中。因此,您首先需要转换数据,然后绘图相当简单。

library(tidyverse)
df1 <- data.frame(white = 48.8, asian = 40)
df1 %>% 
  t() %>% # convert columns to rows
  as.data.frame() %>% # need to change it to a data frame as t() converts it to a matrix
  rownames_to_column("id") %>% 
  ggplot(aes(x = id, y = V1)) +
  geom_col()

导致:

在此处输入图像描述


推荐阅读