R语言时间序列分析:如何让柱状图Y轴显示月度投诉总数
Fixing Y-Axis to Show Monthly Complaint Count Instead of Complaint Names in ggplot2
Looks like you're trying to plot monthly complaint volumes but ended up with complaint names on the Y-axis—let's fix that! The core issue here is how you're mapping variables to the ggplot aesthetics and using statistical functions.
What was wrong with your original code?
- You mapped
Customer.Complaint(a string variable with complaint text) to the Y-axis. ggplot treats this as a discrete variable, so it displays individual complaint names instead of counts. - Using
stat_summary(fun.y=sum)on a string variable doesn't make sense—we need to count complaints per month, not sum text values. - The
scale_y_continuous(labels = fun.y= length)line has incorrect syntax and doesn't align with your goal of showing counts.
Method 1: Pre-aggregate data first (recommended for clarity)
First, calculate monthly complaint counts using dplyr, then plot the aggregated data. This makes your data transformations explicit and easier to debug.
library(ggplot2) library(scales) library(dplyr) # Convert date to proper format comcast$Date <- gsub('-', '/', comcast$Date) comcast$Date <- as.Date(comcast$Date, '%d/%m/%Y') # Create monthly date grouping and count complaints per month comcast_monthly <- comcast %>% mutate(Date_by_month = as.Date(cut(Date, breaks = 'month'))) %>% group_by(Date_by_month) %>% summarise(Complaint_Count = n()) # Count number of complaints per group # Plot the trend ggplot(comcast_monthly, aes(x = Date_by_month, y = Complaint_Count)) + geom_bar(stat = 'identity', fill = '#2c3e50') + scale_x_date(labels = date_format("%Y-%m"), breaks = '1 month') + labs(title = "Monthly Comcast Complaint Trend", x = "Month", y = "Number of Complaints") + theme_minimal()
Method 2: Use stat_count directly in ggplot (no pre-aggregation)
If you want to handle counting entirely within the ggplot call, use stat_count—it automatically counts the number of observations (complaints) for each month. You don't need to map a Y variable here.
library(ggplot2) library(scales) # Date conversion steps comcast$Date <- gsub('-', '/', comcast$Date) comcast$Date <- as.Date(comcast$Date, '%d/%m/%Y') comcast$Date_by_month <- as.Date(cut(comcast$Date, breaks='month')) # Plot with automatic counting ggplot(comcast, aes(x = Date_by_month)) + stat_count(geom = 'bar', fill = '#2c3e50') + scale_x_date(labels = date_format("%Y-%m"), breaks = '1 month') + labs(title = "Monthly Comcast Complaint Trend", x = "Month", y = "Number of Complaints") + theme_minimal()
Key Takeaways
- Map counts to Y-axis: Either pre-calculate the monthly counts (Method 1) or let
stat_counthandle it (Method 2)—don't map raw complaint text to Y. - Use the right statistical function:
n()(count) is what you need here, notsum()(which is for numerical values).
内容的提问来源于stack exchange,提问作者Darkstar Dream
相关产品推荐
相关产品推荐

