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

6
  • 2
    In your own function, add group = Company in aes(). That will work for you. Commented Feb 8, 2018 at 2:25
  • I think this question is almost same to yours. If you want, have a look. Commented Feb 8, 2018 at 2:32
  • 1
    Note that this happens because your x-variable is a factor, and ggplot assumes it should set the group accordingly. Commented Feb 8, 2018 at 8: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 ? Commented Feb 8, 2018 at 13:16
  • 1
    Because the bars aren't being connected. Commented Feb 8, 2018 at 13:39

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.