更改 ggplot2 条形图的顺序(x 轴上带有日期)

问题描述 投票:0回答:2

我有以下数据,并尝试使用 ggplot2 在 R 中创建一个条形图,其中的值与日期值相关

conv = c(10, 4.76, 17.14, 25, 26.47, 37.5, 20.83, 25.53, 32.5, 16.7, 27.33)
click = c(20, 42, 35, 28, 34, 48, 48, 47, 40, 30, 30)

dat <- data.frame(date=c("July 7", "July 8", "July 9", "July 10", "July 11", "July 12", "July 13",
                         "July 14", "July 15", "July 16", "July 17"), click=c(click), conv=c(conv))
dat

但是,当我运行以下命令时,条形图的顺序不正确。

library(ggplot2)
ggplot(dat, aes(date, conv)) +  geom_bar(fill="#336699") + ylim(c(0,50)) +
        opts(title="") +
        opts(axis.text.y=theme_text(family="sans", face="bold", size=10)) +
        opts(axis.text.x=theme_text(family="sans", face="bold", size=8)) +
        opts(plot.title = theme_text(size=15, face="bold")) +
        xlab("") + ylab("")

变量日期正确排序是从7月7日到7月17日,不知道为什么ggplot2有这个问题。有没有一个快速的功能可以解决这个问题,而无需重新排序原始数据集中的数据。

r ggplot2
2个回答
4
投票

您的排序顺序不起作用的原因是您有一个字符串,而不是日期。您最好的选择是将日期转换为日期格式:

dat$date <- as.Date(paste(dat$date, "2011"), format="%b %d %Y")

ggplot(dat, aes(as.character(date), conv)) +  geom_bar(fill="#336699") + 
    ylim(c(0,50)) +
    opts(title="") +
    opts(axis.text.y=theme_text(family="sans", face="bold", size=10)) +
    opts(axis.text.x=theme_text(family="sans", face="bold", size=8, angle=90)) +
    opts(plot.title = theme_text(size=15, face="bold")) +
    xlab("") + ylab("")

enter image description here


0
投票

真实答案: 只需将 ggplot 中的 aes(x = X, y = Y) 更改为 aes(x = reorder(X, -Y), y = Y) (如果你想升序)或 aes(x = reorder(X) , Y), y = Y)(如果您想要降序)

© www.soinside.com 2019 - 2024. All rights reserved.