我有以下数据:
# A tibble: 7 x 2
Time Number
<chr> <dbl>
1 0 hours 7
2 1-5 hours 20
3 6-10 hours 8
4 11-20 hours 13
5 21-40 hours 6
6 40+ hours 3
7 No idea 6
现在,我想用下面的代码(Tidyverse)制作一个直方图:
time_hist = time %>%
ggplot(aes(x=Time, y=Number, fill=Time)) +
geom_bar(width=1, stat="identity") +
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank()) +
labs(fill="Time", x="", y="Number", title = "How much time does this problem cost you?") +
scale_fill_discrete(breaks=c("0 hours", "1-5 hours", "6-10 hours", "11-20 hours", "21-40 hours", "40+ hours", "No idea"))
plot(time_hist)
这导致了下面的直方图:
然而,我希望"6-10小时“的酒吧是第三个酒吧,而不是第六个酒吧。我该如何实现这一点?
发布于 2020-03-18 20:39:33
尝试将Time
转换为一个因子--然后轴将按因子级别的顺序显示。如果您使用forcats::as_factor
(而不是as.factor
),这些级别是按照它们出现的顺序创建的(而不是按字典顺序排序)
library(tidyverse)
time <- tibble::tribble(
~ Time, ~ Number,
"0 hours", 7,
"1-5 hours",20,
"6-10 hours",8,
"11-20 hours",13,
"21-40 hours",6,
"40+ hours",3,
"No idea", 6
)
time <- time %>% mutate(Time = as_factor(Time))
当我使用上面显示的绘图代码时,我现在得到了这个图:
https://stackoverflow.com/questions/60739495
复制相似问题