我有像这样的数据
df <- data.frame (
cancer = c(1, 0, 1, 0, 0, 1, 0, 0, 0, 0),
CVD = c(0, 1, 1, 0, 1, 0, 0, 0, 0, 0),
diab = c(0, 0, 0, 1, 0, 1, 0, 0, 1, 0),
stroke = c(0, 1, 1, 0, 1, 0, 0, 0, 1, 0),
asthma = c(1, 1, 1, 0, 1, 1, 0, 0, 0, 0),
SR_hlt = c(1, 2, 2, 2, 1, 1, 2, 2, 2, 1))
我要做的是制作一个条形图,只为有兴趣疾病的人制作,其中条形图的条形图是按照sr_hlt==1的比例排序的。
为了绘制这个图,我使用以下代码
1)收集数据
df_grp <- df %>%
gather(key = condition, value = Y_N, -SR_hlt) %>%
group_by(condition, Y_N, SR_hlt) %>%
summarise(count = n()) %>%
mutate(freq = round(count/sum(count) * 100, digits = 1))
2)绘制此数据
df_plot <- df_grp %>%
filter(Y_N == 1) %>%
ggplot(aes(x = reorder(condition, -freq), y = freq, fill = factor(SR_hlt)), width=0.5) +
geom_bar(stat="identity", position = position_dodge(0.9))
df_plot
这个
x = reorder(condition, -freq)
应该是命令条的东西,但我认为在这种情况下不起作用,因为freq值依赖于第三个变量sr_hlt的值。是否可以按以下值订购钢筋
freq
当sr_hlt的值=1?