[英]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 没有正确显示。 header1
和header3
中的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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.