【问题标题】:Show data values in barchart with plot_ly使用 plot_ly 在条形图中显示数据值
【发布时间】:2019-05-01 17:55:56
【问题描述】:

我是 plot_ly 的新手,但这个条形图工作正常:

library(plotly)
p <- plot_ly(emo_sum, x=~emotion, y=~count, type="bar", color=~emotion) %>%
  layout(xaxis=list(title=""), showlegend=FALSE,
         title="Testing plot_ly")

现在我正在尝试在每个条形上方显示数据值。我找到了这个例子 How to change axis features in plotly?

它使用一组固定的值,但在我的情况下,它看起来像这样:

library(plotly)
    p <- plot_ly(emo_sum, x=~emotion, y=~count, type="bar", color=~emotion) %>%
add_text(text=~count, hoverinfo='none', textposition = 'top', showlegend = FALSE, 
        textfont=list(size=20, color="black")) %>%
  layout(xaxis=list(title=""), showlegend=FALSE,
         title="Testing plot_ly")

但它不起作用

这里是emo_sum,我贴不上去,每种情绪都有字数:

            count      emotion
anger          120        anger
anticipation   255 anticipation
disgust         85      disgust
fear           170         fear
joy            201          joy
sadness        121      sadness
surprise       106     surprise
trust          298        trust
negative       270     negative
positive       440     positive

【问题讨论】:

  • 您应该提供emo_sum,否则我们无法运行您的代码。
  • 我贴在这里,我想我不能附加文件..
  • 如果您运行 dput(emo_sum) 并在您的问题中打印该输出,我们可以重建该数据集。否则我们将不得不手动重建它。

标签: r r-plotly


【解决方案1】:

您的代码应该可以工作,并且应该在条形上方绘制文本,但我不知道您的原始数据集是什么样子。如果每种情绪有多个值,那么一个条上会有更多的值。然后,您可以按情绪分组并将值相加并显示该总和。

我为您提供了 2 个示例,第一个将文本绘制在条形内,第二个绘制在条形上方:

library(plotly)

## Data
emo_sum <- data.frame(
  emotion=sample(c("anger", "joy", "fear", "anticipation", "disgust", "sadness"), 6, F),
  count=trunc(runif(6,0,100))
)

## Plot text inside Bar
plot_ly(emo_sum, x=~emotion, y=~count, type="bar", color=~emotion,
        text = ~count, textposition = 'auto', insidetextfont = list(size=20, color = 'black')) %>%
  layout(xaxis=list(title=""), showlegend=FALSE,
         title="Testing plot_ly")

## Plot text above Bar
plot_ly(emo_sum, x=~emotion, y=~count, type="bar", color=~emotion) %>%
  add_text(text=~count, hoverinfo='none', textposition = 'top', showlegend = FALSE,
           textfont=list(size=20, color="black")) %>%
  layout(xaxis=list(title=""), showlegend=FALSE,
         title="Testing plot_ly")

【讨论】:

    猜你喜欢
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    • 2014-09-21
    • 2018-02-07
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多