2016-09-22 98 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

相關問題