Reputation: 1946
My data is structured similar to the example below:
Quarter <- c("Q1", "Q2", "Q2", "Q3", "Q4")
Weather <- c("cloudy", "cloudy", "sunny", "sunny", "cloudy")
Duration <- c(16, 10, 12, 15, 14)
WeatherCondData <- data.frame(Quarter, Weather, Duration)
When I plot this data, the second entry for quarter two (Q2
) is sunny however, isn't displayed in sequential order in the plot - cloudy is the second entry.
ggplot(WeatherCondData, aes(x = Quarter, y = Duration, fill = Weather)) +
geom_bar(stat = "identity", position = "stack") +
theme_classic()
How do I change the plot so that sunny is the top part of the stacked bar for Q2?
Thanks.
Upvotes: 1
Views: 74
Reputation: 1360
Use stringsAsFactors = F
to disable auto factor conversion in data.frame()
. Then use factor()
with levels
args to set the order.
WeatherCondData <- data.frame(Quarter, Weather, Duration, stringsAsFactors = F)
WeatherCondData$Weather <- factor(WeatherCondData$Weather, levels=c('sunny','cloudy'))
Upvotes: 3