【问题标题】:How do you increase the space between the axis labels and axis titles in R using functions ggplot() and plot_ly?如何使用函数 ggplot() 和 plot_ly 增加 R 中轴标签和轴标题之间的空间?
【发布时间】:2017-02-05 04:09:12
【问题描述】:

似乎每当我使用包plotly 在R 中创建图形时,轴标题总是覆盖轴标签。我现在有 2 个发生这种情况的图表。我应该使用什么代码来增加使用plot_ly()ggplot() 的轴标题和标签之间的空间?以及如何确保图例在 Plot 1 中可见且不会被截断?

以前的 StackOverflow 问题提供了构建代码的不同方法,但它们似乎不适用于我的代码。

情节 1:

plot <- ggplot(dat, aes(x=HeightUnderCWD, y=GrassHeight))+ geom_point()+ labs(x = "Height under CWD (cm)", y = "Grass Height (cm)")+ theme(text=element_text(size=20, family="Arial"))+ stat_smooth(method = "lm",formula = y ~ x,se = FALSE, color='Darkgreen')+ stat_smooth(aes(x = HeightUnderCWD, y = 7, linetype = "Linear Fit"), method = "lm", formula = y ~ x, se = FALSE,size = 1,color='lightgreen') ggplotly(plot)

情节2:

p<-plot_ly(y = GrassHeight+1, color = CWDPosition,type = "box",colors = "Set1")%>% layout(xaxis = x, yaxis = y, font = f)

【问题讨论】:

  • 您能否提供这些“以前的 StackOverflow 问题”的链接?我没有找到它们。特别是,您的第二个情节的代码不完整(layout(...) 中的xy 应该是一些列表,但它们没有在您的帖子中给出)。
  • 这里是一个非常相关的问题的链接,我提供了一个答案(或者可以称之为“hacky workaround”:p):stackoverflow.com/questions/43229013/…

标签: r plot plotly r-plotly


【解决方案1】:

对于plot_ly,不确定这是最佳答案,但可能是因为左边距太小:

plot_ly(type="box") %>% 
  layout(margin = list(l=25, r=50, b=50, t=50, pad=0),
         yaxis=list(title="GrassHeight")) %>%
  add_trace(y = ~rnorm(50, 0)) %>%
  add_trace(y = ~rnorm(50, 1))

plot_ly(type="box") %>% 
  layout(margin = list(l=100, r=50, b=50, t=50, pad=0),
         yaxis=list(title="GrassHeight")) %>%
  add_trace(y = ~rnorm(50, 0)) %>%
  add_trace(y = ~rnorm(50, 1))

【讨论】: