在大多数多线图中,它绘制一列的多个实体的图表,但在我的情况下,我想绘制单个实体的多个列的图表。
用更简单的术语来说,多线图可能会显示不同国家/地区随时间变化的预期寿命。我想要的是一张图表,显示不同呼叫原因下匹兹堡加班的 EMS 呼叫数量。
大多数多线图看起来像this
但是我希望我的图表看起来像这样(用 Excel 制作):
y 轴是呼叫次数,当然,为了方便和简单起见,我绘制了水平线。
这是我当前使用的软件包。不过,我愿意使用其他软件包。
library(tidyverse)
library(reshape2)
这是我的精简数据(完整数据集有 30 个不同的调用原因)
City_name <- (rep("PITTSBURGH", 6))
year_quarter <- c("2015Q1", "2015Q2", "2015Q3", "2015Q4", "2016Q1", "2016Q2")
ABDOMINAL_PAIN <- rep(10, 6)
ALLERGIES <- rep(12, 6)
ASSAULT <- rep(14, 6)
BACK_PAIN <- rep(16, 6)
df_0 <- tibble(City_name, year_quarter,ABDOMINAL_PAIN, ALLERGIES, ASSAULT, BACK_PAIN)
print(df_0)
# A tibble: 6 × 6
# City_name year_quarter ABDOMINAL_PAIN ALLERGIES ASSAULT BACK_PAIN
# <chr> <chr> <dbl> <dbl> <dbl> <dbl>
# 1 PITTSBURGH 2015Q1 10 12 14 16
# 2 PITTSBURGH 2015Q2 10 12 14 16
# 3 PITTSBURGH 2015Q3 10 12 14 16
# 4 PITTSBURGH 2015Q4 10 12 14 16
# 5 PITTSBURGH 2016Q1 10 12 14 16
# 6 PITTSBURGH 2016Q2 10 12 14 16
# >
我还有一个列名称本身的向量
vec_col.names <- c("ABDOMINAL_PAIN", "ALLERGIES", "ASSAULT", "BACK_PAIN")
我遇到了麻烦,因为大多数来源都像这个那样显示第一种方式。我无法找到其他资源并使用上面来源提供的代码。
north_big <- gapminder %>%
filter(continent == "Americas", country %in% c("United States", "Canada", "Mexico"))
ggplot(north_big, aes(x = year, y = lifeExp, group = country)) +
geom_line(aes(color = country), size = 2)
最简单的方法是这样的:
library(tidyverse)
City_name <- rep("PITTSBURGH", 6)
year_quarter <- c("2015Q1", "2015Q2", "2015Q3", "2015Q4", "2016Q1", "2016Q2")
ABDOMINAL_PAIN <- rep(10, 6)
ALLERGIES <- rep(12, 6)
ASSAULT <- rep(14, 6)
BACK_PAIN <- rep(16, 6)
df_0 <- tibble(City_name, year_quarter, ABDOMINAL_PAIN, ALLERGIES, ASSAULT, BACK_PAIN)
df_long <- df_0 %>%
pivot_longer(cols = ABDOMINAL_PAIN:BACK_PAIN, names_to = "call_reason", values_to = "num_calls")
ggplot(df_long, aes(x = year_quarter, y = num_calls, color = call_reason, group = call_reason)) +
geom_line(size = 1.2) +
labs(title = "Number of EMS Calls in Pittsburgh",
x = "Quarter",
y = "Number of Calls",
color = "Call Reason") +
theme_minimal()
返回