【问题标题】:stacked bar chart in ggplot when converted to plotly doesnt render right转换为 plotly 时,ggplot 中的堆积条形图无法正确呈现
【发布时间】:2017-11-05 10:50:34
【问题描述】:

更新:为数据添加最小可重现代码。

我正在尝试将 ggplot 转换为闪亮的绘图图表。问题是在 ggplot 中,堆积条形图(stat =identity)很好地堆叠在一起,中间没有任何空格,而当我转换为 plotly 时,每个项目之间都有这些空格。

我没有为 Shiny 编写整个代码,因为它很难理解。然而这里是图片和一个非常简化的代码(不是闪亮的版本)

t<- 1:50
GIB_Rating = rep(c('2','3','4+','5','5-','7','8','6','6+','5'),5)
t1<-data.frame(t,GIB_Rating)
CapitalChargeType = c('Credit_risk_Capital','NameConcentration','SectorConcentration')
t2<- expand.grid(t=t, CapitalChargeType=CapitalChargeType)
t3<-left_join(t2,t1)
New = rnorm(150, mean=100,sd=250)
t3<- data.frame(t3,New)

t3<- ggplot(t3, aes(x=GIB_Rating, y=New, fill=CapitalChargeType)) + geom_bar(stat='identity') 
t3

这会产生一些类似这样的图像,这正是我想要的。

但是,由于它不是交互式的,我想要一个绘图图像,当光标悬停在上面时,它会显示资本费用类型的总数。所以,我使用下面的代码

t4<-ggplotly(t3)
t4

现在产生的情节图在每个颜色类(Capitalchargetype)之间有白线(对于每个单独的项目),我想避免这种情况,工具提示也产生单独的项目而不是每个 CapitalChargeType 的总和

【问题讨论】:

  • 您能否提供一个可重现的数据示例?
  • 现在完成。谢谢。

标签: r ggplot2 plotly stacked-chart


【解决方案1】:

问题在于情节处理堆叠的因素条的方式。每个因素都被包裹在一个默认为白色的边框中。有一个非常简单的解决方法:只需将 color = CapitalChargeType 添加到 ggplot 对象即可。

library(tidyverse)
df <- data_frame(
  t = 1:50,
  GIB_Rating = rep(c('2','3','4+','5','5-','7','8','6','6+','5'),5)
)

df <- df %>%
  expand(t, CapitalChargeType = 
c('Credit_risk_Capital','NameConcentration','SectorConcentration')) %>%
  left_join(df) %>%
  mutate(New = rnorm(150, mean=100,sd=250))

g <- ggplot(df, aes(x = GIB_Rating, y = New, fill = CapitalChargeType, color = CapitalChargeType)) + 
  geom_bar(stat='identity') 

plotly::ggplotly(g)

【讨论】:

  • 这可行,但是,工具提示仍然显示单个值,而不是每个 CapitalChargeType 的总和。我意识到解决此问题的一种方法是更改​​数据并绘制计算的组总和,但是是否有我缺少的绘图功能,通过它我可以使工具提示显示总和?感谢您向我展示了创建最小可重现示例的更好方法。
猜你喜欢
  • 1970-01-01
  • 2017-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-28
  • 1970-01-01
相关资源
最近更新 更多