调整ggplot(R)中的垂直网格以匹配所需的值

时间:2017-06-08 11:03:18

标签: r ggplot2

StackOverflow中的第二篇文章,所以我很抱歉不清楚enoguh。

我需要修改ggplot中的垂直网格以匹配某个重复周期的开始和结束(每个dar或每个24h)。我一直在寻找,但我找不到类似的东西。我附上一个代码来运行问题:

mydate <- seq(ISOdate(2016,1,1), ISOdate(2016,2,1), by = "hour") # or "3 months"
mysample <- runif(n = length(mydate), min = 1, max = 10)
mydf <- data.frame(mydate,mysample)
mygraph <- ggplot(data = mydf, aes (x = mydate)) +
              geom_line(aes(y = mysample, colour = "red")) +
              ggtitle("MyTry") +
              labs(x="Day of the Month", y= "MyValue") +
              theme(panel.grid.minor = element_line(colour = "gray50", size = 0.1), 
                    panel.grid.major = element_line(colour = "gray50", size = 0.5), 
                    panel.grid.major.x = element_blank(), 
                    panel.background = element_blank(),
                    axis.text.y = element_text(colour="gray", size = 10),
                    axis.text.x = element_text(vjust = 5, size = 9),
                    plot.title = element_text(hjust = 0.5, size = 20, vjust = 1))
mygraph

哪个给出:

Random values for each hour of a month

如果有人能帮我解决这两个问题,我将不胜感激:

1-。是否可以修改垂直网格(在我的图中只有5个),以便它匹配一天中的每个开始(即00:00:00时间),或者我应该创建数据并将其绘制为“模拟” “一个网格(任何关于此的网站也会受到重视)

2 - 。而不是“ene04”,“ene 11”,“ene 18”......在te X轴上,是否有办法放置所有日期(而不是小时)?所以它出现了“ene 01”“ene 02”等?

我希望我已经说清楚了,所以有人可以帮助我!

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用scale_x_timedate alson控制刻度,并在axis.text.xaxis.ticks.x进行一些调整,您可以将结果粘贴在下面。

library(ggplot2)
library(lubridate)
library(scales)
mydate <- seq(ISOdate(2016,1,1), ISOdate(2016,2,1), by = "hour") # or "3 months"
mysample <- runif(n = length(mydate), min = 1, max = 10)
mydf <- data.frame(mydate,mysample)
mygraph <- ggplot(data = mydf, aes (x = mydate)) +
  geom_line(aes(y = mysample, colour = "red")) +
  ggtitle("MyTry") +
  labs(x="Day of the Month", y= "MyValue") +
  scale_x_datetime(labels = date_format("%b-%d"), breaks=pretty_breaks(n = 32)(as_datetime(c("2016-01-01", "2016-02-01")))) +
  theme(panel.grid.minor = element_line(colour = "gray50", size = 0.1), 
        panel.grid.major = element_line(colour = "gray50", size = 0.5), 
        panel.grid.major.x = element_blank(), 
        panel.background = element_blank(),
        axis.text.y = element_text(colour="gray", size = 10),
          axis.text.x = element_text(size = 9, angle = 270, vjust = -.5),
        axis.ticks.x=element_blank(),
        plot.title = element_text(hjust = 0.5, size = 20, vjust = 1),)
mygraph

enter image description here