繁体   English   中英

如何在 R 每列 dataframe 中创建比例条形图?

[英]How do I create a proportional bar chart in R per columns of a dataframe?

我有一个 dataframe ( df ) 结构如下:

df <- structure(list(header1 = structure(c(2L, 3L, 1L), .Label = c("bad", 
"good", "so-so"), class = "factor"), header2 = structure(c(1L, 
2L, 2L), .Label = c("bad", "good"), class = "factor"), header3 = structure(c(2L, 
1L, 3L), .Label = c("bad", "good", "so-so"), class = "factor")), class = "data.frame", row.names = c(NA, 
-3L))

我一直在尝试使用plot_stackfrq package 中的sjPlot来生成比例条形图。 请注意, header2列缺少任何“一般”值(只有 header1 和 header3 具有so-so值)。 我试过了,但是结果比例条中的 colors 没有正确显示。 header1header3中的so-so对应的颜色在'header2'列中呈现为good对应的颜色。

有没有人使用sjPlot或任何其他可以为每列创建比例条形图的 R 库来解决这个问题?

我不确定它给你带来了什么问题。 我设法生成了以下 plot ,它代表您的示例df中的数据。

library(sjPlot)

# get the index of columns to plot

start <- which(colnames(df)=="header1")

end <- which(colnames(df)=="header3")

plot_stackfrq(df[, start:end])

#If you want to set colors manually 
# plot_stackfrq(df[, start:end], geom.colors = c("#56B4E9", "#009E73", "#0072B2"))
# Assign colors in alphabetical order bad -> good -> so-so. 

数据

df <- structure(list(header1 = structure(c(2L, 3L, 1L), .Label = c("bad", 
"good", "so-so"), class = "factor"), header2 = structure(c(1L, 
2L, 2L), .Label = c("bad", "good"), class = "factor"), header3 = structure(c(2L, 
1L, 3L), .Label = c("bad", "good", "so-so"), class = "factor")), class = "data.frame", row.names = c(NA, 
-3L))

Output

sj图

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM