使用 plotly 创建带有带注释散点的填充区域线图 [英] Create a filled area line plot with annotated scatters using plotly

查看:43
本文介绍了使用 plotly 创建带有带注释散点的填充区域线图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个带有线和散点的填充区域图,如所附屏幕截图中所示,但我不知道如何为 x 轴的每一年添加散点并注释其值.我的代码是:

I want to create a filled area plot with line and scatters like in the screenshot attached but I do not know how could add scatters for every year of x-axis and also annotate its value. My code is:

library(plotly)

data <- t(USPersonalExpenditure)
data <- data.frame("year"=rownames(data), data)

fig <- plot_ly(data, x = ~year, y = ~Food.and.Tobacco, name = 'Food and Tobacco', type = 'scatter', mode = 'line', stackgroup = 'one', fillcolor = '#F5FF8D')
fig

推荐答案

lines+markers+text 模式允许您定义带有标记的线图并添加一些文本.

The mode lines+markers+text allows you to define a line plot with markers and add some text.

我将 year 的类型从因子更改为数字,因为我必须扩展 xaxis 以提高注释的可读性.

I changed the type of year from factor to numeric, because I had to expand the xaxis for readabilty of the annotations.

library(plotly)

data <- t(USPersonalExpenditure)
data <- data.frame("year" = as.numeric(rownames(data)), data)

plot_ly(data,
        x = ~year, 
        y = ~Food.and.Tobacco,
        text = ~Food.and.Tobacco) %>%
  add_trace(
    type = 'scatter',
    mode = 'lines+markers+text',
    fill = 'tozeroy',
    fillcolor = '#F5FF8D',
    marker = list(color = 'black'),
    line = list(color = 'black'),
    textposition = "top center",
    hovertemplate = paste0("<b>%{x}</b>
                           Cummulative Food and Tobacco: %{y} 
                          <extra></extra>"),
    hoveron = 'points') %>%
  layout(xaxis = list(
    range= list(min(data$year) - 1, max(data$year) + 1)))

这篇关于使用 plotly 创建带有带注释散点的填充区域线图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆