0

with a dataframe df like below, Im trying to create a line chart for one of the parameters - Income - in the real data there are other parameters.

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)

I created a function such that I can re-use this - the function takes a dataframe and set of metrics and plot them

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)
}

When I'm using that function by calling plotMetricsLine(df, "Income") - it is giving an empty plot as in the picture below. What is going on wrong here ?

enter image description here

user3206440
  • 4,749
  • 15
  • 75
  • 132
  • 2
    In your own function, add `group = Company` in `aes()`. That will work for you. – jazzurro Feb 08 '18 at 02:25
  • I think [**this question**](https://stackoverflow.com/questions/27082601/ggplot2-line-chart-gives-geom-path-each-group-consist-of-only-one-observation) is almost same to yours. If you want, have a look. – jazzurro Feb 08 '18 at 02:32
  • 1
    Note that this happens because your x-variable is a factor, and `ggplot` assumes it should set the group accordingly. – Axeman Feb 08 '18 at 08:56
  • @Axeman Thanks for the clarification. I notice that for `geom_bar` the plot is fine without setting up `group` - what is the difference for that ? – user3206440 Feb 08 '18 at 13:16
  • 1
    Because the bars aren't being connected. – Axeman Feb 08 '18 at 13:39
  • I got here for some reason. It might be that you have a `character/factor`. Convert it to numeric as follows `as.character(as.numeric(variable))`. – NelsonGon Nov 21 '19 at 19:22

1 Answers1

1

You also need to set group in aes, not just color. This function works:

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")

note the colour so it has different color depending on the factor

Axeman
  • 32,068
  • 8
  • 81
  • 94
Alejandro Andrade
  • 2,196
  • 21
  • 40