无法使用element_line更改线型

时间:2017-11-14 10:02:51

标签: r plot ggplot2 themes

我想创建一个以下列数据为例的情节:

library(data.table)
library(ggplot2)
library(plotly)

Data <- data.table(Datum = c("2017-11-01","2017-11-02","2017-11-03","2017-11-04","2017-11-05","2017-11-06","2017-11-07","2017-11-08","2017-11-09","2017-11-10"),Index = c(200,250,230,210,190,215,216,250,260,245), Long = c(c(250,220,225,215,240,255,256,266,223,222)))
Data$Datum <- as.Date(Data$Datum, format = "%Y-%m-%d")

startdate <- min(Data$Datum)
enddate <- max(Data$Datum)

plot <- ggplot(Data, aes(Datum)) +
  geom_line(aes(y = Index, colour = "Index"), size = 0.5, alpha = 0.5) + 
  geom_line(aes(y = Long, colour = "Long"), size = 0.5, alpha = 0.5) + 
  theme(panel.background = element_rect(fill = "white")) +
  theme(panel.grid.major.x = element_blank(), panel.grid.major.y = element_line(size = 0.5, colour = "grey", linetype = "dotted")) +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  scale_y_continuous(breaks=seq(0,300,20)) + 
  scale_x_date(breaks = seq(as.Date(startdate), as.Date(enddate), by="2 month"), date_labels = "%m %Y") +
  ylab("") +
  xlab("")


plot <- ggplotly(plot)
print(plot)

chart

但正如您在图表中看到的那样,x网格的线型仍然是实线,即使设置为linetype = "dotted"

如何更改线型或我的方法有什么问题?

1 个答案:

答案 0 :(得分:0)

从你的代码中可以看出,绘图在ggplot中按照需要出现,但是一旦转换成plotly就会丢失虚线。正如评论中所提到的,这似乎是plotly的限制。但是,这是您可以使用的解决方法。

由于ggplotly函数可以处理来自geom_line函数的美学,解决此问题的一种简单方法是删除Y行并添加一些手动指定的水平线,如下所示使用geom_hline函数:

plot <- ggplot(Data, aes(Datum)) +
  geom_hline(yintercept =c(200, 220, 240, 260), size = 0.5, colour = "grey", linetype = "dotted") +
  geom_line(aes(y = Index, colour = "Index"), size = 0.5, alpha = 0.5) + 
  geom_line(aes(y = Long, colour = "Long"), size = 0.5, alpha = 0.5) + 
  scale_y_continuous(breaks=seq(0,300,20)) + 
  ylab("") +
  xlab("") +
  theme(panel.background = element_rect(fill = "white"),
        panel.grid.major.x = element_blank(),
        panel.grid.major.y = element_blank())

plot <- ggplotly(plot)
print(plot)

enter image description here

查看here以获取有关geom_line函数的更多文档。

您可以添加以通过查找最大和最小y值然后创建序列来自动确定行间距,而不是手动指定步骤:

min.plot <- roundUP(min(Data$Index,Data$Long),10) - 20
max.plot <- max(Data$Index,Data$Long) + 20
y.axis <- seq(from = min.plot, to = max.plot, by = 10)

并将geom_hline参数编辑为:

geom_hline(yintercept = y.axis, size = 0.5, colour = "grey", linetype = "dotted")