我正在尝试在R中构建一个支出跟踪器。数据框有三个属性,即日期,金钱和类别。我已经成功制作了一个堆积的条形图,其中x轴=日期和y轴=花费的总和,但我在将类别标记为不同(不重复)方面遇到了麻烦。
这是我的代码:
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
)
答案 0 :(得分: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)