【问题标题】:Plot including one categorical variable and two numeric variables包含一个分类变量和两个数值变量的绘图
【发布时间】:2016-01-11 22:31:47
【问题描述】:

如何在图表上显示其对应类型的 AverageTime 和 AverageCost 的值。变量的规模是不同的,因为其中一个是时间的平均值,另一个是成本的平均值。我想将类型定义为 x,y 指的是 AverageTime 和 AverageCost 的值。 (在这种情况下,我将在一张图中有两个线图)

Type<-c("a","b","c","d","e","f","g","h","i","j","k")
AverageTime<-c(12,14,66,123,14,33,44,55,55,6,66)
AverageCost<-c(100,10000,400,20000,500000,5000,700,800,400000,500,120000)
df<-data.frame(Type,AverageTime,AverageCost)

【问题讨论】:

  • @MLavoie,非常感谢您的回复。我想在一张图中有两个线图,x 是指类型的级别,线图 1 显示 AverageTime 的值,条形图 2 显示 Averagecost 的值。
  • 是要显示每个 x 的平均值还是要显示每个字母的两个值
  • @MLavoie:我想显示每种类型的两个值。
  • 你说得对,我修改了问题。
  • 您仍然可以使用我的答案,但只需替换名称

标签: r algorithm


【解决方案1】:

这可以使用facet_wrapscales="free_y" 来完成,如下所示:

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

df %>%
  mutate(AverageCost=as.numeric(AverageCost), AverageTime=as.numeric(AverageTime)) %>%
  gather(variable, value, -Type) %>%
  ggplot(aes(x=Type, y=value, colour=variable, group=variable)) +
  geom_line() +
  facet_wrap(~variable, scales="free_y")

您可以在此处比较两条线,即使它们的比例不同。

HTH

【讨论】:

  • 感谢您的回复,但我更喜欢将类型设置为“x”以更好地查看 Averagecost 和 AverageTime 的趋势。我的意思是我想在一个图中有两条条线。
  • 感谢您的出色解决方案,我想知道您为什么在解决方案中使用 summarise(value.mean=mean(value)) ,因为我们没有重复的类型。
  • 以前数据集的痕迹。现已编辑。
  • @shoorideh 你能说明你在哪里以及如何使用is.na()吗?
  • @boshek,我解决了这个问题。再次感谢您的出色解决方案。
【解决方案2】:
# install.packages("ggplot2", dependencies = TRUE)
library(ggplot2)
p <- ggplot(df, aes(AverageTime, AverageCost, colour=Type)) + geom_point()
p + geom_abline()

【讨论】:

  • 感谢您的帮助,但我想将类型定义为 x,y 指的是 AverageCost 和 AverageTime。然后我可以看到,每个级别类型的 AverageTime 和 AverageCost 的值。
  • 您能否重新表述您正在寻找的内容,或者以某种方式说明它?
【解决方案3】:

要在同一个图中显示两条线会很困难,因为它们的比例不同。您还需要将 AverageTime 和 AverageCost 转换为数值变量。

library(ggplot2)
library(reshape2)
library(plyr)

为了能够在一张图中绘制两条线并取两条线的平均值,您需要进行一些整形。

df_ag <- melt(df, id.vars=c("Type"))
df_ag_sb <- df_ag %>% group_by(Type, variable) %>% summarise(meanx = mean(as.numeric(value), na.rm=TRUE))

ggplot(df_ag_sb, aes(x=Type, y=as.numeric(meanx), color=variable, group=variable)) + geom_line()

【讨论】:

  • 感谢您的帮助,不幸的是,我在数据集中犯了一个错误。我现在修改问题。
猜你喜欢
  • 2023-03-08
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-28
  • 1970-01-01
  • 1970-01-01
  • 2023-01-08
相关资源
最近更新 更多