R plotly - 显示不同的标签

问题描述 投票:0回答:1

我正在尝试在R中构建一个支出跟踪器。数据框有三个属性,即日期,金钱和类别。我已经成功制作了一个堆积的条形图,其中x轴=日期和y轴=花费的总和,但我在将类别标记为不同(不重复)时遇到了麻烦。

Here现在是图表的样子,我希望标签只显示为A,B,C。

这是我的代码:

    dff<- data.frame(today= Sys.Date(), money = 222 , category = "B")
    new_dat<- data.frame(today= Sys.Date()-1, money = 111, category = "A")
    dff<- rbind(dff,new_dat)
    new_dat<- data.frame(today= Sys.Date()-1, money = 222, category = "C")
    dff<- rbind(dff,new_dat)


    plot_ly(dff, type = "bar", x = ~today, y = ~money, color = ~category) %>%
  add_trace(y= ~today, name= ~category) %>%
  layout(barmode = 'stack') %>%
  add_annotations(text = ~money,
                  x = ~today,
                  y = ~money,
                  xref = 'today',
                  yref = 'money',
                  font = list(family = 'Arial', size = 12,
                              color = 'rgb(67, 67, 67)'),
                  showarrow= FALSE
                  )
r label plotly
1个回答
0
投票

我想你只需要将showlegend = FALSE添加到第二个跟踪中。你想要这个吗?

a<- plot_ly(dff, type = "bar", x = ~today, y = ~money, color = ~category) %>%
    add_trace(y= ~today, name= ~category, showlegend = FALSE) %>%
    layout(barmode = 'stack')

a

编辑:对于您的后续问题,您可以尝试这样做:

a<- plot_ly(dff, type = "bar", x = ~today, y = ~money, color = ~category) %>%
  add_trace(y= ~today, name= ~category, showlegend = FALSE) %>%
  layout(barmode = 'stack') %>%   
add_annotations(xref = 'x', yref = 'y',
                x = "2018-04-15", y = ~money - 50,
                text = paste(dff[,"money"], '$'),
                font = list(family = 'Arial', size = 12,
                color = 'rgb(248, 248, 255)'),
                showarrow = FALSE) %>% 
add_annotations(xref = 'x', yref = 'y',
                x = "2018-04-16", y = "111",
                text = paste("222", '$'),
                font = list(family = 'Arial', size = 12,
                            color = 'rgb(248, 248, 255)'),
                showarrow = FALSE)
© www.soinside.com 2019 - 2024. All rights reserved.