簡體   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