如何在R中为多个数据框列创建比例条形图?

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

我有一个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库可以为每列创建比例条形图的解决方案吗?

r
1个回答
0
投票
我不确定这给您带来什么问题。我设法产生了下面的图,它代表了样品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))

输出

sjPlot

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