我有一个R数据帧,其结构如下:
header1 header2 header3
good bad good
so-so good bad
bad good so-so
我一直在尝试使用sjPlot R库中的plot_stackfrq函数来生成比例条形图。请注意,header2列缺少任何“一般”值。因为在header2列中仅显示2个类别,所以所得比例条形图中的颜色显示不正确。例如,与“ header1”和“ header3”中的“ so-so”相对应的颜色表示为与“ header”列中与“ good”相对应的颜色。
有人使用sjPlot或另一个R库可以为每列创建比例条形图的解决方案吗?
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))
输出