You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R ggplot2调整图例排序及X轴完整展示2017-2021年份标签咨询

问题修复方案

1. 图例自定义排序

你在将category列转为因子时没有手动指定层级,导致默认按字段首字母排序。直接在转因子时指定你需要的顺序即可:

five_years_growth$category <- factor(five_years_growth$category, 
                                     levels = c("Sales", "Gross Profit", "EBITDA", "EBIT", "Net Profit before Tax"))

2. X轴完整显示2017-2021年份标签

你将year列转为了日期格式,ggplot默认会自动计算轴刻度间隔,只需要添加scale_x_date配置手动指定每年显示一个刻度即可:

scale_x_date(name = "Financial Year", date_breaks = "1 year", date_labels = "%Y")

完整可运行代码

# 加载包(安装包代码仅需首次运行,后续使用可注释)
# install.packages("tidyverse")
# install.packages("lubridate")
# install.packages("scales")
library(tidyverse)
library(lubridate)
library(dplyr)
library(scales)
library(ggplot2)

# 读取并处理数据
five_years_growth <- read.csv("five_years_growth.csv")
five_years_growth$year <- dmy(five_years_growth$year)
five_years_growth$amount <- as.numeric(five_years_growth$amount)
# 手动指定category因子层级,控制图例顺序
five_years_growth$category <- factor(five_years_growth$category, 
                                     levels = c("Sales", "Gross Profit", "EBITDA", "EBIT", "Net Profit before Tax"))

# 绘图
ggplot(data = five_years_growth) +
  geom_col(mapping = aes(x = year, y = amount, fill = category), 
           position = position_dodge(width = 0.8)) +
  # 配置X轴,每年显示一个刻度,仅展示年份
  scale_x_date(date_breaks = "1 year", date_labels = "%Y") +
  scale_y_continuous(name = "Amount $", label = comma) +
  labs(title = "Key Performance : 2017 to 2021", x = "Financial Year")

内容的提问来源于stack exchange,提问作者Virajk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 07:39:01