0
votes

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

1
In your own function, add group = Company in aes(). That will work for you. - jazzurro
I think this question is almost same to yours. If you want, have a look. - jazzurro
Note that this happens because your x-variable is a factor, and ggplot assumes it should set the group accordingly. - Axeman
@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
Because the bars aren't being connected. - Axeman

1 Answers

0
votes

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