Posts

Showing posts with the label ggplot2

Fix: ggplot2: Display per Months using Stacked Bar Chart with

 To create a stacked bar chart in `ggplot2` displaying data per month, you can use the `geom_bar()` function and map your data to the `x` (months) and `fill` (categories) aesthetics. Here's a step-by-step example: Assuming you have a data frame called `df` with columns `month`, `category`, and `value`, where `month` is a Date or DateTime, `category` represents the categories you want to stack, and `value` represents the values: ```R library(ggplot2) # Sample data df <- data.frame(   month = seq(as.Date("2023-01-01"), as.Date("2023-12-01"), by = "1 month"),   category = c("A", "B", "C"),   value = c(10, 20, 30, 15, 25, 35, 5, 10, 15, 20, 25, 30) ) # Create a ggplot2 stacked bar chart ggplot(df, aes(x = month, y = value, fill = category)) +   geom_bar(stat = "identity") +   labs(     title = "Stacked Bar Chart per Month",     x = "Month",     y = "Value",     fill = "Category&q

proportion plot by date or week for different groups with ggplot2

 To create a proportion plot by date or week for different groups using `ggplot2` in R, you can use the `geom_bar` and `facet_grid` or `facet_wrap` functions. Here's an example of how you can do this: Assuming you have a dataset named `data` with columns `Date`, `Group`, and `Value`, and you want to create a proportion plot by date or week for different groups: ```R # Load required libraries library(ggplot2) library(dplyr) # Convert the Date column to a Date object if it's not already data$Date <- as.Date(data$Date) # If you want to group by week, you can use lubridate library(lubridate) data$Week <- week(data$Date) # Calculate proportions within each group and date/week data <- data %>%   group_by(Group, Date, Week) %>%   summarise(Proportion = sum(Value) / sum(data$Value)) # Create the proportion plot ggplot(data, aes(x = Date, y = Proportion, fill = Group)) +   geom_bar(stat = "identity", position = "dodge") +   facet_wrap(~Group, scales =