plot - Issues with ggplot in ggplotly package in R: missing legend and no spaces between axis and labels -
when run following code, produces graph:
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)
for reason, cannot increase spaces between axis labels , graph, though have tried many different ways using vjust
. , can see semblance of legend in right hand corner. cant see entire thing nor can zoom out. there issue above code?
this subset of data:
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
if @ plot object see missing legend defined scale_fill_manual named 'my lines' there wrong ggplot code before convert it. instead printing 'linear fit' second stat_smooth layer (see ?linetype valid values of linetype.)
to correct try putting color in aes mapping (similiar alistaire highlighted).
reference: ggplot2: missing legend , how add?
then you'll want use scale_***_manual 'color' instead of 'fill' create custom legend. matches aes mapped earlier stat_smooth.
reference: r: custom legend multiple layer ggplot
revised code:
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)
if still don't after convert plotly, can adjust margins/padding on plotly object using 'layout' function. don't need save object , modify object details directly. examples on plot.ly site show how add without saving first.
example command using examples:
ggplotly(plot) %>% layout(autosize=f,margin=list(l=50,r=50,b=50,t=50,pad=5))
references:
https://plot.ly/r/setting-graph-size/
https://plot.ly/r/reference/#layout-margins
Comments
Post a Comment