我使用ggplot和ggplotly()绘制了此条形图
它以我想要的方式呈现,它按模式类型和年份显示总崩溃的总和。
但是,我正在努力(悬停)工具提示来显示总崩溃数的总和。现在,它只显示“ 1”。
我需要对我的代码做些什么,以配置工具提示以显示如图所示的总崩溃次数,而不是值1?这是我的代码,以及它产生的条形图:
crashplot <- ggplot(totcrashes_by_year, aes(totcrashes_by_year$`Crash Year`, totcrashes_by_year$`Total Crashes`))
crashplot +geom_bar(stat = "identity",
aes(fill=totcrashes_by_year$`Mode Type`), position = "stack") + xlab("Crash Year") + ylab("Total Crashes") + ggtitle("Total Crashes by Year and Mode Type") + labs(fill = "Mode Type")
编辑:可复制代码示例 这是用于复制此问题的代码。
crashsample <- data.frame(year = sample(2007:2018, 40, replace = T),
crashes = 1,
type = sample(c('Vehicle', 'Pedestrian','Bike','Motorcycle'), 5, replace = TRUE))
crashplot <- ggplot(crashsample, aes(x = year, y = crashes, fill = type)) +
geom_bar(stat = "identity") +
labs(x = 'Crash Year',
y = 'Total Crashes',
title = "Total Crashes by Year and Mode Type",
fill = "Mode Type")
#call to ggplotly to render as a dynamic plotly chart
ggplotly(crashplot)
答案 0 :(得分:1)
此代码为我返回有效标签
# Simulate Data
df <- data.frame(year = sample(2005:2015, 20, replace = T),
crashes = sample(30:100, 20),
type = sample(c('Vehicle', 'Pedestrian'), 20, replace = TRUE))
# Required packages
require(plotly); require(tidyverse)
# ggplot2 plot definition
crashplot <- df %>%
group_by(year, type) %>%
summarise(summed_crashes = sum(crashes)) %>%
ggplot(., aes(x = year, y = summed_crashes, fill = type)) +
geom_bar(stat = 'identity') +
labs(x = 'Crash Year',
y = 'Total Crashes',
title = 'Total Crashes by Year and Mode Type',
fill = "Mode Type")
# Show plot with plotly
ggplotly(crashplot)
如果它不起作用,那么很高兴看到此问题的可重现数据示例。