我正在绘制数据集与ggplot2中的日期,y轴为日期。我希望按时间倒序排列日期。最早的日期位于y轴的顶部。另外,我想以我想要的方式格式化日期。
我遇到的麻烦是我相信我需要scale_y_continuous()和scale_y_reverse才能完成此任务,但它们并不能很好地协同工作。我在我的情节中尝试的是:
... ggplot setup ... +
scale_y_continuous(label=function(juldate) strftime(chron(juldate), "%Y-%m-%d")) +
scale_y_reverse()
我得到的错误是:
Scale for 'y' is already present. Adding another scale for 'y', which will replace the existing scale.
如何让格式化和反转一起工作?请注意,在此示例中,y轴是julian日期整数,这是我尝试让事情一起工作的最后一次尝试。
独立地,scale_y ...语句执行它应该做的事情,无论是正确格式化还是反转轴,但我不能同时使用它们。
感谢任何帮助。
谢谢, 马特
ADDED:可重复的例子
library("ggplot2")
library("chron")
# Data to graph. Want to show a calendar, days on the left
# and candle lines showing the duration of each event.
work <- rbind(
data.frame(ydate_start=15480, ydate_end=15489, event="Event One"),
data.frame(ydate_start=15485, ydate_end=15499, event="Event Two")
)
# Formats nicely, but I want order of dates reversed
ggplot(work,
aes(x=event,
y=ydate_start,
ymin=ydate_start,
ymax=ydate_end,
color=event)
) +
geom_linerange() +
ylab("Date") +
scale_y_continuous(label=function(x) strftime(chron(x), "%Y-%m-%d"))
# Order reversed, but no formatting applied
ggplot(work,
aes(x=event,
y=ydate_start,
ymin=ydate_start,
ymax=ydate_end,
color=event)
) +
geom_linerange() +
ylab("Date") +
scale_y_reverse()
# Both delarations don't play well together well
ggplot(work,
aes(x=event,
y=ydate_start,
ymin=ydate_start,
ymax=ydate_end,
color=event)
) +
geom_linerange() +
ylab("Date") +
scale_y_continuous(label=function(x) strftime(chron(x), "%Y-%m-%d")) +
scale_y_reverse()
#> Scale for 'y' is already present. Adding another scale for 'y', which will replace the existing scale.
答案 0 :(得分:0)
我解决了自己的问题。我必须有一个错误或者没有以某种方式正确地尝试过这个,但解决方案是scale_y_reverse()将'label'作为参数,就像scale_y_continuous一样。以下作品:
library("ggplot2")
library("chron")
# Data to graph. Want to show a calendar, days on the left
# and candle lines showing the duration of each event.
work <- rbind(
data.frame(ydate_start=15480, ydate_end=15489, event="Event One"),
data.frame(ydate_start=15485, ydate_end=15499, event="Event Two")
)
# THIS SOLVES THE PROBLEM
ggplot(work,
aes(x=event,
y=ydate_start,
ymin=ydate_start,
ymax=ydate_end,
color=event)
) +
geom_linerange() +
ylab("Date") +
scale_y_reverse(label=function(x) strftime(chron(x), "%Y-%m-%d"))