【发布时间】:2017-07-17 15:15:18
【问题描述】:
我想在演示文稿中显示 x 轴标签列表的每一秒。 下面的简化代码示例及其在图 1 中的输出,其中显示了四个日期,但应跳过 #2 和 #4。
# https://stackoverflow.com/a/6638722/54964
require(ggplot2)
my.dates = as.Date(c("2011-07-22","2011-07-23",
"2011-07-24","2011-07-28","2011-07-29"))
my.vals = c(5,6,8,7,3)
my.data <- data.frame(date =my.dates, vals = my.vals)
plot(my.dates, my.vals)
p <- ggplot(data = my.data, aes(date,vals))+ geom_line(size = 1.5)
预期输出:跳过第二个和第四个日期。
实际代码
由于rev(Vars) 逻辑,我无法将as.Date 应用于每个类别中的值的实际代码;变量molten 有一列Dates
p <- ggplot(molten, aes(x = rev(Vars), y = value)) +
geom_bar(aes(fill=variable), stat = "identity", position="dodge") +
facet_wrap( ~ variable, scales="free") +
scale_x_discrete("Column name dates", labels = rev(Dates))
预期输出:跳过每个类别中的 #2、#4、... 值。
我想在这里将scale_x_discrete 更改为scale_x_continuous 并在scale_x_continuous 中有一个中断序列breaks = seq(1,length(Dates),2)) 但由于以下错误而失败。
Error: `breaks` and `labels` must have the same length
基于 Juan 的 cmets 的建议
代码
ggplot(data = my.data, aes(as.numeric(date), vals)) +
geom_line(size = 1.5) +
scale_x_continuous(breaks = pretty(as.numeric(rev(my.data$date)), n = 5))
输出
Error: Discrete value supplied to continuous scale
将 EricWatt 的提案应用测试为实际代码
代码提案
p <- ggplot(molten, aes(x = rev(Vars), y = value)) +
geom_bar(aes(fill=variable), stat = "identity", position="dodge") +
facet_wrap( ~ variable, scales="free") +
scale_x_discrete("My dates", breaks = Dates[seq(1, length(Dates), by = 2)], labels = rev(Dates))
输出
Error: `breaks` and `labels` must have the same length
如果你有scale_x_discrete("My dates", breaks = Dates[seq(1, length(Dates), by = 2)]),你会得到没有任何标签的 x 轴,所以空白。
图。 1 简化代码示例的输出, 图 2 EricWatt 的第一个提案的输出
操作系统:Debian 9
R:3.4.0
【问题讨论】:
-
试试
scale_x_continuous(breaks=pretty(rev(Vars), length(Vars)/2)) -
对不起!除非您通过过于复杂的
as.Date,否则这不适用于日期。 @EricWatt 的答案是你应该使用的。 -
每个链接的答案,如果你打电话给
as.numeric,例如ggplot(data=my.data, aes(as.numeric(date), vals)) + geom_line() + scale_x_continuous(breaks=pretty(as.numeric(rev(my.data$date)))),它就可以工作,但是你可能想添加标签,我觉得这太复杂了! -
抱歉,
pretty需要指定断点数,所以加上pretty(..., n=4)。 -
Here it is 带标签:
ggplot(data=my.data, aes(as.numeric(date), vals)) + geom_line(size=1.5) + scale_x_continuous(breaks=pretty(as.numeric(rev(my.data$date)), n=4), labels=format(rev(my.data$date), format="%m/%d/%y"))
标签: r ggplot2 debian axis-labels