[英]Plotly markers to appear in a bar chart
我是新手,想制作自己的项目符号图表(有点像http://bl.ocks.org/mbostock/4061961 ),其中包含标记/迹线,用于在比较实际值与预期值时显示相关值的值。
以下是我的尝试:
q <- ggplot(data.frame(measure='',actual=25),aes(x=measure,y=actual))+
geom_bar(stat='identity')+
ylim(c(0,35))+
geom_hline(yintercept = 30,color='red')+
geom_text(y=30,label='Expected',angle=270,vjust=0)+
coord_flip()+
ylab('Num. of carrots')
q
q1 <- ggplotly(q) %>% add_markers()
q1
当使用ggplotly
将其转换为plotly时,文本看起来好像没有正确旋转,并且条形图没有显示标记/迹线...这里的任何帮助将不胜感激。
最亲切的问候,
HLM
我不认为plotly支持为type =“ scatter”旋转文本(这是ggplotly解释您的geom_text
)。 您可以从ggplot图中删除geom_text
行,然后使用注释将文本添加到绘图中:
q1 <- ggplotly(q) %>% add_markers() %>%
layout(annotations = list(x = 30, y = 1, text = "Expected", textangle=270))
q1
问题的第二部分(如何在栏上也获得悬停信息)比较棘手。 要获取悬停信息,我们可以像这样直接使用plotly API创建条形图
p.bars = plot_ly(data = data.frame(measure='', actual=25)) %>%
add_bars(y=~measure, x=~actual, orientation="h")
我们可以像这样添加文本注释
p.bars.text = p.bars %>%
layout(annotations = list(x = 30, y = 0, text = "Expected", textangle=270,
showarrow=F, xanchor="center"))
但是问题在于,还通过
p.bars.text %>% add_segments(x=30, xend=30, y=-0.5, yend=0.5)
给出一个错误
populate_categorical_axes(p)中的错误:无法在同一轴上同时显示离散数据和非离散数据
即,我们只能相对于y的分类值指定线的y值。 因此,例如我们可以
dat1 = data.frame(measure=letters[1:2], actual=c(25,20))
plot_ly(data = dat1) %>%
add_bars(y=~measure, x=~actual, orientation="h") %>%
layout(annotations = list(x = 29, y = 0, text = "Expected", textangle=270,
showarrow=F, xanchor="center")) %>%
add_segments(x=30, xend=30, y='a', yend='b')
这给出以下内容,其中该行与类别标签而不是条的宽度对齐
目前,我对此的唯一解决方案是对类别使用数字轴,然后使用ticktext设置轴标签:
plot_ly(data = data.frame(measure=c(0,1), actual=c(25,20))) %>%
add_bars(y=~measure, x=~actual, orientation="h", showlegend=F) %>%
add_segments(x=30, xend=30, y=-0.4, yend=0.4, showlegend=F) %>%
layout(annotations = list(x = 29.5, y = 0, text = "Expected", textangle=270, showarrow=F, xanchor="center"),
yaxis = list(tickmode="array", tickvals=c(0,1), ticktext=c("", "") ))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.