[英]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.