如何使用数字输入来控制直方图上绘制垂直线的位置?

时间:2018-10-26 18:32:22

标签: r r-plotly ggplotly

所以我有一个直方图,但是我想添加一个标量栏或文本输入框,以使垂直线以指定的频率出现。我不确定该怎么做。我尝试使用abline,但收到一条错误消息,提示尚未创建图。

下面是我的直方图代码。

---
title: "Untitled"
output: 
  flexdashboard::flex_dashboard:
    orientation: rows
    social: menu
    source_code: embed
---

```{r setup, include=FALSE}
library(ggplot2)
library(plotly)
library(maps)
knitr::opts_chunk$set(message = FALSE)
```

Column {data-width=600}
-------------------------------------

### Historgram of Victim Age

```{r}
#Loading the data
df <- read.delim2("https://www.chapelhillopendata.org/explore/dataset/police-incident-reports-written/download/?format=csv&refine.date_of_report=2017&timezone=America/New_York&use_labels_for_header=true", sep = ";")

#Converting `Victim.Age` from factor to numeric 
df <- df %>% 
        filter(!is.na(Victim.Age)) %>%
        mutate(
                Victim.Age = as.numeric(levels(Victim.Age))[Victim.Age])
```

```{r}
# provide a custom tooltip to plotly with the county name and actual rate
p <- qplot(df$Victim.Age,
           geom = "histogram",
           binwidth = 0.5,
           main = "Histogram for Victim Age",
           xlab = "Age (Yrs)",
           ylab = "Frequency", 
           fill = I("blue"),
           col = I("red"),
           alpha = I(0.2),
           xlim = c(0, 80))

# just show the text aesthetic in the tooltip
ggplotly(p, tooltip = "text")

1 个答案:

答案 0 :(得分:0)

我不知道我是否正确理解了您想要什么,但是可以使用geom_vline()在ggplot2中创建一条垂直线。

例如,在平均年龄中包含一条垂直线,如下所示:

p1 <- p + geom_vline(aes(xintercept = mean(Victim.Age, na.rm = TRUE)))

ggplotly(p1, tooltip = "text")