【问题标题】:ggplot in plotly behaves differentlyplotly 中的 ggplot 表现不同
【发布时间】:2017-05-17 14:16:40
【问题描述】:

我在 ggplot 中使用以下代码制作了一个绘图。这是数据源 https://www.dropbox.com/s/xzauims7rqwurga/who_ghg_complete.csv?dl=0

p1 <- ghg_complete %>% 
  filter(`Country Name` %in% c("United States", "China", "India")) %>% 
  ggplot(aes(x = year, y = Emissions, 
             group = `Country Name`, color = `Country Name`)) +
  geom_point(size = 2, shape = 21) +
  geom_line() +
  labs(title = "Greenhouse gas emissions (kt of CO2 equivalent)",
       x = NULL,
       y = NULL) +
  scale_x_discrete(breaks = seq(1970, 2012, by = 5)) +
  theme_bw() +
  theme(legend.position = "bottom") +
  scale_color_brewer(palette = "Set1")
p1

这是输出:- 当我在 ggplotly 中包装相同的情节时

ggplotly(p1)

情节表现不同。图例看起来不一样,并且 y 轴上的数字被剪掉了。

我按照 cmets 中的建议更改了 y 轴编号,但仍然无法解决问题。 代码如下:

p1 <- ghg_complete %>% 
  filter(`Country Name` %in% c("United States", "China", "India", "Nepal")) %>% 
  ggplot(aes(x = year, y = Emissions, 
             group = `Country Name`, color = `Country Name`)) +
  geom_point(size = 2, shape = 21) +
  geom_line() +
  labs(title = "Greenhouse gas emissions (kt of CO2 equivalent)",
       x = NULL,
       y = NULL) +
  scale_x_discrete(breaks = seq(1970, 2012, by = 5)) +
  theme_bw() +
  scale_color_brewer(palette = "Set1")
# Convert ggplot object to plotly
gg <- plotly_build(p1) %>% 
  layout(legend = list(orientation = 'h', y = -0.1))
gg

剧情如下:-

【问题讨论】:

  • 这就是传说中的情节。不要认为你可以做很多事情。虽然剪裁是一个错误,但以兆吨或千兆吨为单位不是更好吗?这对我的老眼睛来说太多了。
  • @MikeWise 不是你的眼睛......有太多的零是可以理解的......或者我的眼睛也老了:-)
  • 另外:为什么您期望 plotly 能够为您提供与您定制的 ggplot 绘图相同的结果?
  • 现在到处都是无用的sn-ps代码是怎么回事?没用,因为它们只是 Javascript...
  • 我转换了单位,但这对 y 轴数字没有帮助。有什么建议么?有没有更好的方法可以在不使用 plotly 的情况下使 ggplot 绘图具有交互性。

标签: r ggplot2 plotly


【解决方案1】:

ggplotly() 并不完全将您的 ggplot 图复制到 plotly 中,它使 plotly 等效。如果你想确保你的 plotly 图看起来像你的 ggplot 图,你需要在 plotly 中进一步调整它。例如,要使图例看起来更相似,您可以将 %&gt;% layout(legend = list(orientation = 'h', x = 0.35, y = -0.1)) 添加到您的 ggplotly 调用中。您可能需要调整 xy 值以完全按照您的喜好排列图例。

正如 Mike Wise 在 cmets 中针对轴标签的裁剪建议的那样,您最好只表示以兆吨或千兆吨为单位的值,这样它们就没有那么多的 0

【讨论】:

  • 感谢@Marijn Stevering,帮助了传奇。
猜你喜欢
  • 2017-09-10
  • 2018-02-19
  • 2019-05-28
  • 2016-08-16
  • 2015-04-08
  • 1970-01-01
  • 2018-09-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多