【问题标题】:How to use + geom_line() with a categorical x-variable and quantitative y-variable [duplicate]如何将 + geom_line() 与分类 x 变量和定量 y 变量一起使用 [重复]
【发布时间】:2020-06-17 14:16:23
【问题描述】:

如何使用 ggplot 2 创建 折线图,其中 x 变量是分类变量或因子,y 变量是数字变量,组变量是分类变量?我已经尝试使用上述变量 + geom_point() 并且它有效,但 + geom_line() 没有。

我已经查看过以下帖子: Creating line graph using categorical data, ggplot2 bar plot with two categorical variablesNo line in plot chart despite + geom_line(),但他们都没有回答我的问题。

在我进入代码和示例之前,(1) 是的,我绝对必须将 x 变量和组变量作为字符或因子,(2) 不,我不想要条形图或只是 geom_point()。

下面的示例提供了来自三个不同示例回归的多个自变量的系数,这些示例使用因变量的不同变体运行。虽然下面的代码显示了我想出的解决方法(即创建一个名为“test”的 int 变量来代替包含回归的自变量名称的 chr 变量),但我需要能够保留自变量的 chr 名称。

这是我所拥有的:

library(dplyr)
library(ggplot2)
library(plotly)
library(tidyr)

var_names <- c("ST1", "ST2", "ST3", 
               "EFI1", "EFI2", "EFI3", "EFI4", 
               "EFI5", "EFI6")

####Dataset1####
reg <- c(26441.84, 20516.03, 12936.79, 17793.22, 18837.48, 15704.31, 17611.14, 17360.59, 14836.34)
r_adj <- c(30473.17, 35221.43, 29875.98, 30267.31, 29765.9, 30322.86, 31535.66, 30955.29, 29828.3)
a_adj <- c(19588.63, 31163.79, 22498.53, 27713.72, 25703.89, 28565.34, 29853.22, 29088.25, 25213.02)

df1 <- data.frame(var_names, reg, r_adj, a_adj, stringsAsFactors = FALSE)
df1$test <- c(1:9)

df2 <- gather(df1, key = "series_type", value = "value", c(2:4))

fig7 <- ggplot(df2, aes(x = test, y = value, color = series_type)) + geom_line() + geom_point()
fig7

最终我想要一些看起来像下图的东西,但用自变量名称代替“测试”变量。

Example Plot

【问题讨论】:

  • 对于 aes() 中的 x,我想你想要 x = factor(test)
  • @jazzurro 事实证明,x 变量是一个因素还是一个字符并不重要(我尝试了两种方式都没有成功)。重要的是确保在 aes() 中包含“group = series_type”参数。我认为 color = series_type 会涵盖这一点,但您必须包含 group = series_type 才能使 geom_line() 工作。

标签: r ggplot2


【解决方案1】:

您可以将var_names 转换为因子并按出现顺序设置级别(否则它将按字母数字分配,x 轴将无序)。然后只需将series_type 添加到图中的组参数中即可。

df2 <- gather(df1, key = "series_type", value = "value", c(2:4)) %>%
  mutate(var_names = factor(var_names, levels = unique(var_names)))

ggplot(df2, aes(x = var_names, y = value, color = series_type, group = series_type)) + geom_line() + geom_point()

【讨论】:

  • 所以事实证明我缺少的部分是将“group = series_type”添加到 ggplot() 的 aes() 中。无论 x 变量是 chr 还是因子,添加 group 参数都有效。
猜你喜欢
  • 2019-10-07
  • 2020-10-03
  • 2020-09-25
  • 2010-11-13
  • 2019-11-13
  • 2020-07-16
  • 1970-01-01
  • 2019-10-21
  • 2021-03-17
相关资源
最近更新 更多