【问题标题】:Stacked horizontal barchart plotly堆积水平条形图
【发布时间】:2020-04-10 11:56:29
【问题描述】:

我正在尝试使用以下数据绘制水平条形图:

这是我迄今为止尝试创建的代码,但我不确定如何完成其​​余部分,或者我是否做得对:

data <- data.frame(Answer = c("Have more than enough money", "Have enough money", "Have just enough money", "Do not have enough money", "Prefer not to answer"), 
                   City_Total = c(11,34,34,16,4), 
                   Auckland = c(11,30,35,19,5), 
                   Hamilton = c(10,28,41,16,5), 
                   Tauranga = c(12,38,35,12,4),
                   Hutt = c(12,39,31,14,3), 
                   Porirua = c(10,36,29,19,5), 
                   Wellington = c(16,42,28,11,3),
                   Christchurch = c(11,41,31,13,4),
                   Dunedin = c(12,41,34,11,2))

【问题讨论】:

    标签: r rstudio plotly r-plotly ggplotly


    【解决方案1】:

    您可以使用ggplot 制作情节并使用ggplotly()

    require(plotly)
    require(dplyr)
    
    data <- data.frame(Answer = c("Have more than enough money", "Have enough money", "Have just enough money", "Do not have enough money", "Prefer not to answer"), 
                       City_Total = c(11,34,34,16,4), 
                       Auckland = c(11,30,35,19,5), 
                       Hamilton = c(10,28,41,16,5), 
                       Tauranga = c(12,38,35,12,4),
                       Hutt = c(12,39,31,14,3), 
                       Porirua = c(10,36,29,19,5), 
                       Wellington = c(16,42,28,11,3),
                       Christchurch = c(11,41,31,13,4),
                       Dunedin = c(12,41,34,11,2))
    m_data <- melt(data)
    
    g <- ggplot(m_data,aes(x=variable, y=value, fill=Answer)) +
      geom_bar(position="stack", stat="identity") + 
      coord_flip() +
      theme_minimal()
    
    ggplotly(g)
    

    【讨论】:

    • 融化(数据)错误:找不到函数“融化”
    • @Raisham, melt 可能来自包reshape2
    • 是的,刚刚发现了!