【问题标题】:Add multi-layered ticklabels to plotly xaxis for timeseries添加多层刻度标签以绘制时间序列的 x 轴
【发布时间】:2021-11-16 14:31:04
【问题描述】:

我想将 xaxis 标签添加到看起来像附加图像的情节中。请注意月份和年份的不同刻度角度以及合并的年份值(我在 excel 中制作了图)。

目前在我的情节中,我可以将月份-年份分成两条线,但有没有办法将月份倾斜 90 度并合并类似于 excel 的年份。下面是一些示例数据和我从 plotly 得到的当前输出。

library(plotly)
dates <- seq.Date(as.Date("2020-01-01"), as.Date("2021-12-31"), 7)
set.seed(42)
values <- rnorm(105, 10, 2)

data.frame(dates = dates, values = values) %>%
  plot_ly(x=~dates, y=~values) %>% 
  add_lines() %>% 
  layout(xaxis = list(dtick = "M1", ticklabelmodel = "period" , tickformat = "%b<br>%Y", tickangle = 0))

【问题讨论】:

    标签: r charts formatting plotly


    【解决方案1】:
    • 我无权访问 R 环境,因此在 python 中回答
    • 使用多类别轴。这是作为 x 参数传递的二维数组
    • 更新布局以旋转多类别轴第一部分的文本
    df = pd.DataFrame({"date":pd.date_range("1-jan-2020", freq="M", periods=23), "value":np.random.uniform(2,5,23)})
    
    fig = go.Figure(go.Scatter(x=[df["date"].dt.year, df["date"].dt.strftime("%b") ], y=df["value"]))
    fig.update_layout(xaxis={"tickangle":-90})
    
    

    【讨论】:

    • 我使用了一个列表来传递 xaxis 值,但现在无法将日期返回到月份 tibble(dates = dates, values = values) %&gt;% mutate(year = lubridate::year(dates)) %&gt;% plot_ly(x=~ list(year, dates), y=~values) %&gt;% add_lines()
    • 如果我使用月份列,则该月的积分会相互叠加。 tickformat 不适用于数组。
    猜你喜欢
    • 1970-01-01
    • 2020-09-28
    • 2020-10-12
    • 1970-01-01
    • 2012-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多