使用带有手动数据帧的ggplot创建条形图,一行5列

问题描述 投票:0回答:1

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9QRHlMMi5wbmcifQ==” alt =“在此处输入图像描述”>

这是我的数据框。我找不到一种使用ggplot并以列名和x作为指示值来构造条形图的方法。

r dataframe ggplot2 data-visualization data-wrangling
1个回答
0
投票

如评论中所述,张贴代码/数据/错误的图像是一种不良做法。我只复制了数据框的前两个条目。通常,对于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()

结果:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.