barplot() 中的排序条 [英] Ordering bars in barplot()
问题描述
我有一个数据框,其中一个变量(我们称之为 Q1)有几个级别:不使用"、30 分钟"、1 小时"、2 小时"、3+ 小时".
I have a dataframe, and one of the variables (let's call it Q1) has several levels: "No use", "30 min", "1 hour", "2 hours", "3+ hours".
如何绘制条形图(),条形图按因子水平顺序排列?我尝试使用 sort(),但这并不能解决问题.
How can I plot a barplot(), where the bars are in the order of factor levels? I tried using sort(), but that doesn't do the trick.
根据要求,一些示例数据:
As requested, some sample data:
Q1
1 hour
1 hour
30 min
2 hours
3+ hours
3+ hours
3+ hours
3+ hours
2 hours
1 hour
2 hours
1 hour
30 min
我试过了:
barplot(table(sort(Q1)), main = "Q1 Answer Distribution", ylim = c(0, 250), cex.axis=0.9)
但它没有给我我需要的东西.
but it doesn't give me what I need.
推荐答案
正如 Henrik 所说,您需要将数据放入一个因子中(至少这是实现这一目标的最简单方法).考虑以下带有一些虚假数据的示例...
As stated by Henrik, you need to get your data into a factor (at least this is the easiest easiest way to make this happen). Consider the following example with some fake data...
#generate 1000 random uniform integers between 1 and 5
data <- floor(runif(1000, 1,6))
#make data a factor with given labels
fdata <- factor(data,
labels = c("No use",
"30 min",
"1 hour",
"2 hours",
"3+ hours"))
这可以在带有 plot 的 base r 中完成(未指定 y 时不需要 barplot)
This can be done in base r with plot (barplot is not required when y is not specified)
#in base R, just use plot - when y is missing, barplot is produced
plot(fdata)
您也可以在 ggplot2 中绘图
You can also plot in ggplot2
#in ggplot2
require(ggplot2)
#make a dataframe
df <- data.frame(id = seq(1:length(fdata)),
fdata = fdata)
#plot via geom_bar
ggplot(df, aes(fdata)) + geom_bar()
从您的原始示例继续,除了指定级别外,您还需要设置 ordered=TRUE
,如下所示.否则,无用"仍会显示在您的列表末尾.
Proceeding from your original example, in addition to specifying levels, you are going to need to set ordered=TRUE
as shown below. Otherwise, "No use" will still show up at the end of your list.
#get data into a factor (provided data plus "No use")
q1 <- c("No use"
,"1 hour"
,"1 hour"
,"30 min"
,"2 hours"
,"3+ hours"
,"3+ hours"
,"3+ hours"
,"3+ hours"
,"2 hours"
,"1 hour"
,"2 hours"
,"1 hour"
,"30 min")
q1f = factor(q1,
levels = c("No use",
"30 min",
"1 hour",
"2 hours",
"3+ hours"),
ordered=TRUE)
然后你可以应用上面显示的绘图逻辑...
Then you can apply the plot logic shown above...
这篇关于barplot() 中的排序条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!