我是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
答案 0 :(得分:0)
您的代码应该可以工作,并且应该在条形图上方绘制文本,但是我不知道您原始的数据集是什么样子。如果每种情绪有多个值,那么在一个小节上会有更多的值。然后,您可以按情感进行分组并汇总这些值,然后显示该总和。
我为您提供了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")