ggplot - geom_line没有绘制线

时间:2018-02-08 02:18:56

标签: r ggplot2

如下所示的数据框df,我尝试为其中一个参数创建折线图 - Income - 在实际数据中还有其他参数。

text <- "
Parameter,Company, Qtr, Value
Income, Comp1, Q1FY18, 100
Income, Comp1, Q2FY18, 110
Income, Comp1, Q3FY18, 130
Income, Comp2, Q1FY18, 60
Income, Comp2, Q2FY18, 70
Income, Comp2, Q3FY18, 90
"
df <- read.table(textConnection(text), sep=",", header = T,
                 stringsAsFactors = F)

我创建了一个函数,以便我可以重复使用它 - 该函数采用数据框和一组指标并绘制它们

plotMetricsLine <- function(df, metrics) {
  df <- df %>%
    filter(Parameter %in% metrics)
  p <- ggplot(data=df, aes(x=Qtr, y=Value,color = Company)) +
    geom_line(size=1)
  return(p)
}

当我通过调用plotMetricsLine(df, "Income")使用该功能时 - 它正在给出一个空图,如下图所示。这里出了什么问题?

enter image description here

1 个答案:

答案 0 :(得分:0)

您还需要在group中设置aes,而不仅仅是颜色。这个功能有效:

plotMetricsLine <- function(df, metrics) {
  df <- df%>%filter(Parameter %in% metrics)
  p <-ggplot(data=df, aes(x=Qtr, y=Value,group = as.factor(Company),colour=Company)) +
    geom_line(size=1)
  return(p)
}
plotMetricsLine(df, "Income")

请注意colour,因此根据因素

,它会有不同的颜色
相关问题