2016-09-22 42 views
0

当我运行下面的代码时,它产生该曲线图:问题与ggplot在ggplotly包中R:缺少图例和轴之间没有空格和标签

plot <- ggplot(dat, aes(x = HeightUnderDebris, y = GrassHeight)) + 
    geom_point() + 
    stat_smooth(method = 'lm', se = FALSE,color = 'darkgreen') + 
    stat_smooth(aes(x = HeightUnderDebris, y = 5, linetype = "Linear Fit"), 
       method = "lm", formula = y ~ x, se = F, size = 1, color = 'lightgreen') + 
    labs(x = "Height under CWD (cm)", y = "Grass Height (cm)")+ 
    scale_fill_manual(name = 'My Lines', values = c("darkgreen", "lightgreen")) + 
    theme(axis.title.x = element_text(color = "black", vjust = -1), 
      axis.title.y = element_text(vjust = 0.5)) 
ggplotly(plot) 

enter image description here

出于某种原因,我不能增加轴标签和图形之间的空间,即使我尝试了许多不同的方法,使用vjust。我可以在右上角看到一些传说的外表。但我不能看到整个事物,也不能缩小。我的上面的代码有问题吗?

这是我的数据的一个子集:

GrassHeight HeightUnderCWD 0 0 0 0 0 0 8 16 0 0 0 0 0 0 2 2 6 6 0 0 0 0 1 1 0 0 0 0 0 0 8 15 0 0 7 7 15 15

+1

要获得ggplot一个图例你需要被映射到可变'color','fill',或'aes'内的'linetype'。 Plotly可能会覆盖你的间距,所以你应该使用'layout'来调整它。此外,你应该在你的问题中提供足够的数据以使其[重现](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)。 – alistaire

+0

您可以通过在控制台中运行'p $ data'和'p $ layout'来检查所有设置,其中'p'是您的图形对象。数据是人类可读的。您也可以通过这种方式更改设置,例如:'p $ layout $ title < - “我的图标题”'。并非所有可能的设置仅列出具有值的设置。欲了解更多检查情节页 – Siemkowski

+0

@ alistaire,感谢您的意见。我添加了我的数据的一个子集,以便您可以尝试重现它 – Dominique

回答

1

如果你看一下剧情对象本身,你会看到一个缺少你“我行”命名scale_fill_manual定义所以传说在转换之前,您的ggplot代码有问题。相反,它会从第二个stat_smooth图层打印“线性拟合”(请参见线型的有效值的线型)。

要更正尝试将您的颜色放入aes映射中(类似于Alistaire突出显示的内容)。

参考: ggplot2: missing legend and how to add?

那么你还需要使用规模_ *** _手册“色”,而不是“补”来创建自定义的传奇。这与您之前使用stat_smooth映射的aes匹配。

参考:R: Custom Legend for Multiple Layer ggplot

修改后的代码:

plot <- ggplot(dat, aes(x = HeightUnderCWD, y = GrassHeight)) + 
    geom_point() + 
    stat_smooth(aes(color = 'darkgreen'),method = 'lm', se = FALSE,) + 
    stat_smooth(aes(x = HeightUnderCWD, y = 5,color='lightgreen'), 
     method = "lm", formula = y ~ x, se = F, size = 1) + 
    scale_color_manual(name = 'My Lines', 
     values =c("darkgreen"="darkgreen", "lightgreen"="lightgreen"), 
     labels=c("GrassHeight 5cm","Linear Fit")) + 
    labs(x = "Height under CWD (cm)", y = "Grass Height (cm)")+ 
    theme(axis.title.x = element_text(color = "black", vjust = -1), 
     axis.title.y = element_text(vjust = 0.5)) 

#check plot 
plot 

ggplotly(plot) 

如果你仍然将其转换为plotly,您可以在plotly对象上使用调整页边距/填充后不喜欢看的“布局“功能。您不需要直接保存对象并修改对象的详细信息。 plot.ly网站上的示例显示如何添加而不先保存。

示例命令使用它们的实例:

ggplotly(plot) %>% layout(autosize=F,margin=list(l=50,r=50,b=50,t=50,pad=5)) 

参考文献:
https://plot.ly/r/setting-graph-size/
https://plot.ly/r/reference/#layout-margins

相关问题