如何在 R 中使用 ggplot2 创建具有双 X 轴的绘图?

问题描述 投票:0回答:1

我正在尝试在 R 中创建一个显示两个重叠 X 轴的图:

  • 一个用于 Semana TW(今年的几周)。
  • 一个用于 Semana LY(去年的几周)。 目标是将过去 7 周的销售额与上一年同周的销售额进行比较,但向前移动了 3 周(这就是为什么我在 Semana TW 列中有三个零销售额)。

我能够使用 matplotlib 在 Python 中创建此图表,但我需要使用 ggplot2 或其他绘图库在 R 中复制它。 这是我用 Python 生成的图表: enter image description here

这是我使用的数据表:

台湾周 周岁 文塔台湾 文塔LY
W1 WA 1000 1100
W2 WB 800 700
W3 厕所 900 1000
W4 WD 1000 1100
W5 我们 1100 1000
W6 WF 1000 1100
W7 工作组 900 1000
W8 WH 0 1100
W9 WI 0 1000
W10 WJ 0 1200

在 R 中,我尝试了这段代码,它给了我类似的结果,但这不是我想要的:

library(ggplot2)
library(tidyr)

# Data setup with correct sorting for Semana TW
Semana_TW <- factor(c('W1', 'W2', 'W3', 'W4', 'W5', 'W6', 'W7', 'W8', 'W9', 'W10'), levels = c('W1', 'W2', 'W3', 'W4', 'W5', 'W6', 'W7', 'W8', 'W9', 'W10'))
Semana_LY <- c('WA', 'WB', 'WC', 'WD', 'WE', 'WF', 'WG', 'WH', 'WI', 'WJ')
Venta_TW <- c(1000, 800, 900, 1000, 1100, 1000, 900, 0, 0, 0)
Venta_LY <- c(1100, 700, 1000, 1100, 1000, 1100, 1000, 1100, 1000, 1200)

# Create the initial data frames for Semana TW and Semana LY
df_TW <- data.frame(Semana = Semana_TW, Ventas_TW = Venta_TW)
df_LY <- data.frame(Semana = Semana_LY, Ventas_LY = Venta_LY)

# Merge the two datasets
df_combined <- data.frame(
  Semana_TW = Semana_TW,
  Semana_LY = Semana_LY,
  Ventas_TW = Venta_TW,
  Ventas_LY = Venta_LY
)

# Convert the data into long format for ggplot (for easy plotting of both series)
df_combined_long <- pivot_longer(df_combined, cols = c("Ventas_TW", "Ventas_LY"), 
                                 names_to = "Tipo_Venta", values_to = "Ventas")

# Create the plot using ggplot2
ggplot(df_combined_long, aes(x = Semana_TW, y = Ventas, color = Tipo_Venta, group = Tipo_Venta)) +
  geom_line() + # Create the line connecting the points
  geom_point() + # Add points for each week
  labs(title = "Ventas Semanas TW vs LY", x = "Semana TW", y = "Ventas") +
  theme_minimal() +
  scale_color_manual(values = c("Ventas_TW" = "blue", "Ventas_LY" = "red")) +
  geom_text(aes(label = Semana_LY), vjust = -1, hjust = 1.1, angle = 45) + # Annotate with Semana LY values
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

enter image description here

r ggplot2 plot
1个回答
0
投票

我们可以使用连续的 x 尺度和

sec.axis
参数:

ggplot(
  df_combined_long, 
  aes(x = as.numeric(Semana_TW), y = Ventas, color = Tipo_Venta, group = Tipo_Venta)
) +
  geom_line() + # Create the line connecting the points
  geom_point() + # Add points for each week
  labs(title = "Ventas Semanas TW vs LY", x = "Semana TW", y = "Ventas") +
  theme_minimal() +
  scale_color_manual(values = c("Ventas_TW" = "blue", "Ventas_LY" = "red")) +
  scale_x_continuous(
    breaks = 1:nlevels(Semana_TW),
    labels = Semana_TW,
    sec.axis = sec_axis(I, breaks = 1:nlevels(Semana_TW), labels = Semana_LY)
  ) +
    theme(
    axis.text.x = element_text(angle = 45, hjust = 1),
    axis.text.x.top = element_text(angle = 45, hjust = 0)
  )

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.