Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting a bar chart with smoothing line using ggplot in R

Tags:

r

ggplot2

I am working in R. I have build a data frame based on two vectors. That is used to create a scatter chart with a smoothing line (plot1). This works without problems. But I need a bar chart with a smoothing line as well. The plot gets drawn, but without a smoothing line (plot2).

library(ggplot2)

# Fill two vectors month and sale
month_short <- substr(month.name,1,3)
month <- factor(month_short, levels=month_short)
sales <- c(3189.0, 3063.0, 1084.6, 3151.80, 352.0, 5915.55, 2619.9, 493.0, 758.5, 45.0, 1704.0, 2608.0)

# Build dataframe
df <- data.frame(month, sales)
df

# Scatter chart with ggplot
plot <- ggplot(data=df, aes(x=month, y=sales, group=1)) + 
  labs(title="Sales to UK in 2015",x = "Month", y = "Sales (EUR)") +
  geom_line() +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE) 
plot

# Bar chart with ggplot
plot2 <- ggplot(data=df, aes(x=month, y=sales)) + 
  labs(title="Sales to UK in 2015",x="Month", y = "Sales (EUR)") +
  geom_col() +
  geom_smooth(method = "lm", se = FALSE)
plot2
like image 218
Steve Avatar asked Mar 09 '26 04:03

Steve


1 Answers

You will need the aes(group=1) options just like the first plot. You can add it specifically to the geom_smooth layer

ggplot(data=df, aes(x=month, y=sales)) + 
  labs(title="Sales to UK in 2015",x="Month", y = "Sales (EUR)") +
  geom_col() + 
  geom_smooth(aes(group=1), method = "lm", se = FALSE)

enter image description here

like image 85
MrFlick Avatar answered Mar 11 '26 07:03

MrFlick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!