Reputation: 31
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
Upvotes: 3
Views: 3016
Reputation: 206167
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)
Upvotes: 4