R - 带有 geom_bar 的 ggplotly 在将光标移动到条形图上时显示错误的 y 轴值



>我有以下代码创建条形图:

require(data.table)
require(plotly)
require(ggplot2)
df1 <- data.table(Time = seq(50, 290, 30), Enter = c(155000, 400000, 950000, 950000, 1000000, 1100000, 1100000, 1100000, 1150000), 
Exit = c(150000, 165000, 167000, 225000, 500000, 560000, 562000, 564000, 590000))
df1 <- melt(df1[,c('Time','Enter','Exit')],id.vars = 1)
df1$Time <- as.factor(df1$Time)
df1$value <- format(df1$value, format="f", big.mark=",", scientific = F, digits = 0)
# Create Barplot of In and outflows
ggplotly(tooltip = c("y", "x", "colour"), p =
ggplot(df1, aes(x = Time, y = value)) + 
geom_bar(aes(fill = variable), stat = 'identity', position = 'dodge', colour = 'black') + 
scale_fill_manual(name = "", labels = c('Enter', 'Exit'), values= c('chartreuse4', 'brown')) +
labs(x = 'Time', y ='Value')) 

当我将鼠标光标移动到条形以查看条形具有哪个值时,它不显示(即对于第一个绿色条(155,000 而是 2。为什么会这样,我该如何修复它以使其显示正确的数字?

我认为该值必须转换为因子!然后它应该可以正常工作。

库和数据:

require(data.table)
require(plotly)
require(ggplot2)
df1 <- data.frame(Time = seq(50, 290, 30), Enter = c(155000, 400000, 950000, 950000, 1000000, 1100000, 1100000, 1100000, 1150000), 
Exit = c(150000, 165000, 167000, 225000, 500000, 560000, 562000, 564000, 590000))

解决方案 1:以因子格式使用value

df1 <- melt(df1[,c('Time','Enter','Exit')],id.vars = 1)
df1$Time <- factor(df1$Time)
#df1$value <- format(df1$value, format="f", big.mark=",", scientific = F, digits = 0)
# Create Barplot of In and outflows
ggplotly(tooltip = c("y", "x", "colour"), p =
ggplot(df1, aes(x = Time, y = value)) + 
geom_bar(aes(fill = variable), stat = 'identity', position = 'dodge', colour = 'black') + 
scale_fill_manual(name = "", labels = c('Enter', 'Exit'), values= c('chartreuse4', 'brown')) +
labs(x = 'Time', y ='Value')) 

解决方案 2:要保持value为数字格式,但仍使用逗号分隔的正确tooltip,请使用以下版本:

df1 <- melt(df1[,c('Time','Enter','Exit')],id.vars = 1)
df1$Time <- factor(df1$Time)
df1$value <- format(df1$value, format="f", big.mark=",", scientific = F, digits = 0)
# Create Barplot of In and outflows
p=ggplot(df1, aes(x = Time, y = value, text = paste0("Value:", value)) ) + 
geom_bar(aes(fill = variable), stat = 'identity', position = 'dodge', colour = 'black') + 
scale_fill_manual(name = "", labels = c('Enter', 'Exit'), values= c('chartreuse4', 'brown')) +
labs(x = 'Time', y ='Value')
ggplotly(p, tooltip = c("x","text"))

相关内容

  • 没有找到相关文章