我想在演示文稿中显示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
并在breaks = seq(1,length(Dates),2))
中设置了中断序列scale_x_continuous
,但由于以下错误而失败。
Error: `breaks` and `labels` must have the same length
代码
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
代码提案
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答案 0 :(得分:3)
这适用于您的简化示例。如果没有您的molten
data.frame,很难根据更复杂的情节进行检查。
ggplot(data = my.data, aes(date, vals)) +
geom_line(size = 1.5) +
scale_x_date(breaks = my.data$date[seq(1, length(my.data$date), by = 2)])
基本上,使用scale_x_date
可能会为您处理数字转换的任何奇怪日期。
答案 1 :(得分:1)
我的解决方案最终取决于其他链接线程和EricWatt的回答所激发的实际代码
# Test data of actual data here # https://stackoverflow.com/q/45130082/54964
ggplot(data = molten, aes(x = as.Date(Time.data, format = "%d.%m.%Y"), y = value)) +
geom_bar(aes(fill = variable), stat = "identity", position = "dodge") +
facet_wrap( ~ variable, scales="free") +
theme_bw() + # has to be before axis text manipulations because disables their effect otherwise
theme(axis.text.x = element_text(angle = 90, hjust=1),
text = element_text(size=10)) +
scale_x_date(date_breaks = "2 days", date_labels = "%d.%m.%Y")