【问题标题】:How to use a numeric input to control where a vertical line is plotted over my histogram?如何使用数字输入来控制在直方图上绘制垂直线的位置?
【发布时间】:2018-10-26 18:32:21
【问题描述】:

所以我有一个直方图,但我想添加一个标量栏或文本输入框,以便在指定频率处出现一条垂直线。我不知道该怎么做。我尝试使用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")

【问题讨论】:

    标签: r r-plotly ggplotly


    【解决方案1】:

    我不知道我是否正确理解了您想要的内容,但是可以使用geom_vline() 制作 ggplot2 中的垂直线。

    例如,平均年龄中的一条垂直线是这样包含的:

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

    【讨论】: