ggplot和ggplotly之间图例位置的区别是什么?

19

我发现了一个有趣而奇怪的区别,即在ggplot和ggplotly中相同的图表显示不同。

Translated:

我发现了一个有趣而奇怪的区别,即在ggplot和ggplotly中相同的图表显示不同。

income_gap_chart <- ggplot(income_gap, aes(x = Country, y = Percent, fill = Income)) + 
geom_bar(position = "dodge", stat = "identity") +
scale_fill_brewer(palette = "Set1") +
coord_flip() +
theme(axis.title.y = element_blank()) +
scale_y_continuous(limits = c(0, 100)) +
theme_tufte() +
theme(axis.title.y = element_blank()) +
theme(legend.position = "bottom")

对于ggplot,底部的图例标题看起来非常完美

enter image description here

但是当我用ggplotly()包装它时,图例开始表现出不同的行为

enter image description here

我的问题是 - 我想要第一个图以ggplotly格式显示,但无法解决这个问题,并且底部的图例不起作用。 有什么想法吗?

谢谢!


2
似乎这是一个未解决的问题:https://github.com/ropensci/plotly/issues/1049 - RLave
2个回答

20

在一些R专家的帮助下,问题很快得到了解决。

添加了这个。

ggplotly(income_gap_chart) %>% layout(legend = list(orientation = "h", x = 0.4, y = -0.2))

结果:enter image description here

谢谢!


6
这个解决方案中没有图例标题。 - pogibas
@PoGibas,如果有人能添加另一个解决方案 - 那太好了!我得到了期望的结果。 - Anakin Skywalker
2
我遇到了错误:Error in layout(., legend = list(orientation = "h", x = 0.4, y = -0.2)) : unused argument (legend = list(orientation = "h", x = 0.4, y = -0.2)) - PM0087
@PeyM87,谢谢,很抱歉听到这个消息。我已经有一年多没有碰那段代码了,所以可能自那时起他们更新了一些东西,不能保证它现在能正常工作。请查看文档。谢谢! - Anakin Skywalker

4

评论中指出该解决方案似乎省略了图例标题。通过在 layout() 中包含 title = ... 很容易修复此问题:

diamonds_chart <- ggplot(diamonds, aes(x = cut, y = carat, fill = color)) + 
  geom_bar(position = "dodge", stat = "identity")
  
diamonds_chart %>% 
  ggplotly %>% 
  layout(
    legend = list(
      orientation = 'h', x = 0.3, y = -0.1, 
      title = list(text = 'My legend title')
      )
    )

enter image description here


谢谢。我三年前问过这个问题,希望他们已经改进了! - Anakin Skywalker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接