如何用ggplot绘制堆叠柱状图展示各年份不同状态员工的平均工龄
Hey there! Let's put together that stacked bar chart using ggplot2 for your employee data. I'll break this down into simple, actionable steps so you can follow along easily.
Step 1: Create a proper data frame from your raw data
First, we need to structure your raw data into an R data frame that ggplot can work with:
# Build the employee data frame employee_data <- data.frame( year = c(2011, 2011, 2012, 2012, 2013, 2013), status = c(0, 1, 0, 1, 0, 1), exp = c(8.40, 6.66, 7.49, 5.78, 6.48, 4.51) ) # Optional: Convert status to meaningful labels (makes the chart easier to interpret) employee_data$status <- factor(employee_data$status, levels = c(0, 1), labels = c("离职员工", "留任员工"))
If you prefer to keep the original 0/1 labels for status, just skip the second code block.
Step 2: Install and load ggplot2
If you haven't already installed the ggplot2 package, run this once:
install.packages("ggplot2")
Then load the package for use:
library(ggplot2)
Step 3: Create the stacked bar chart
Here's the code to generate your desired plot, with explanations of key parts:
ggplot(employee_data, aes(x = factor(year), y = exp, fill = status)) + geom_col(position = "stack") + # Use geom_col for pre-calculated values (like your average tenure) labs( x = "年份", y = "平均工龄", title = "各年份离职与留任员工平均工龄堆叠图", fill = "员工状态" ) + theme_minimal() # Clean, minimalist theme (swap for theme_bw() or theme_classic() if preferred)
factor(year): Treats year as a discrete category instead of a continuous number, so the x-axis only shows the years you have data for.position = "stack": Ensures bars for each status are stacked on top of one another (this is the default behavior for geom_col, so you can omit this argument if you want).labs(): Adds clear, descriptive labels to make your chart easy to understand.
内容的提问来源于stack exchange,提问作者Ramesh Soundararajan
相关产品推荐
相关产品推荐

