【问题标题】:Names Argument Plotly Barplot名称参数 Plotly 条形图
【发布时间】:2016-11-14 14:21:57
【问题描述】:

所以我在 Shiny 中使用 Plotly 创建条形图。但是 x 标签不是唯一的,例如(Dog 两次):

设 df 为:

x     y
1     Dog
2     Cat
3     Dog
3     Ant
4     Bee

我希望绘制所有行,但这不起作用,因为 x 列中有重复的变量 Dog:

p = plot_ly(df, x = df[,2],  y = df[,1], type = "bar", marker = list(color = toRGB("blue")))
p

所以我正在考虑通过以下方式解决这个问题: 我可以通过删除 x 参数来绘制所有 5 行。然后我希望能够分别修改这些名称来填写x列变量。

p = plot_ly(df,  y = x, type = "bar", marker = list(color = toRGB("blue")))
p

如何手动更改 plotly barplot 中的 x 标签?

谢谢

【问题讨论】:

    标签: r label shiny bar-chart plotly


    【解决方案1】:

    直截了当的官方方法:

    layout 中为xaxis 使用tickmodetickvalsticktext 参数:

    library(plotly)
    plot_ly(df, y = x, type = "bar", 
            marker = list(color = toRGB("blue"))) %>% 
             layout(xaxis = list(tickmode = "array",
                                 tickvals = 0:4,
                                 ticktext = c("Dog", "Cat", "Dog", "Ant", "Bee")))
    

    我不确定上述命令中的y = x 在其他类型的绘图中的推广效果如何。因此,我推荐这种方法:

    # change the y labels (I assigned "a", "b" etc.) 
    df$y <- letters[1:nrow(df)]
    
    
    df %>% plot_ly(x = y,  y = x, type = "bar", 
                   marker = list(color = toRGB("blue"))) %>% 
                   layout(xaxis = list(tickmode = "array",
                                       tickvals = c("a", "b", "c", "d", "e"),
                                       ticktext = c("Dog", "Cat", "Dog", "Ant", "Bee")))
    

    短技巧:

    只需在第二次出现 dog 的末尾添加一个空格:

    df$y <- as.character(df$y)
    df[3,2] <- "Dog "
    

    然后你可以使用你的第一个绘图命令:

    plot_ly(df, x = df[,2],  y = df[,1], type = "bar", marker = list(color = toRGB("blue")))
    

    我检查了这两种方法的图,它们看起来一样。 显然,您的实际应用程序可能不会这么简单,而且黑客可能不可行。

    另外,您始终可以使用ggplot2,然后使您的绘图与plotly::ggplotly 交互

    【讨论】:

    • 太棒了,使用第一种方式,效果很好。非常感谢。
    猜你喜欢
    • 2021-06-28
    • 2021-12-28
    • 2021-10-27
    • 2021-11-28
    • 2018-01-06
    • 2020-08-25
    • 1970-01-01
    • 2016-02-25
    • 2018-08-22
    相关资源
    最近更新 更多