首页 文章

转换为plotly时,ggplot中的堆积条形图不会向右渲染

提问于
浏览
0

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

我试图将ggplot转换为有光泽的情节图表 . 问题是在ggplot中,堆叠的条形图(带有stat = identity)很好地堆叠,中间没有任何空格,而当我转换为plotly时,每个项目之间都有这些空格 .

我没有制作闪亮的整个代码,因为很难遵循 . 然而,这里是图像和一个简化的代码(不是闪亮的版本)

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

这会产生一些像这样的图像,这正是我想要的 .
enter image description here

然而,由于它不是交互式的,我想要一个图形图像,它显示光标悬停时的总资本费用类型 . 所以,我使用下面的代码

t4<-ggplotly(t3)
t4

现在生成的阴谋图在每个颜色类(Capitalchargetype)之间都有白线(对于每个单独的项),我想避免,工具提示也产生单个项而不是每个CapitalChargeType的总和
enter image description here

1 回答

  • 0

    问题在于如何处理堆积的因素 . 每个因子都包含在一个默认为白色的边框中 . 有一个非常简单的解决方法:只需将 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)
    

    plotly output

相关问题