使用geom_rect的彩色的背景

时间:2016-08-02 13:48:05

标签: r plot ggplot2

我想根据不同的因素为线条图(geom_line)的背景着色。在这个例子中,我突出了基于一年中4个季节的时间序列图的背景。

我指定不同季节的矩形位置,但我无法指定填充颜色。我指出了每个季节的颜色,但是情节包含了与我选择的颜色不同的颜色。

你知道我做错了吗?

# Create a dataset
Iteration <- seq (1:24)
Values <- runif (24, 0, 1)
Season <- rep (c( rep("winter", 3), rep ("Summer", 3), rep ("Autumn", 3), rep ("Winter", 3)),2)
df <- data.frame (Iteration, Values, Season) ; df

# Indicate the seasons in the X axis
start_spring <- which(Season == "Spring") ; end_spring <- start_spring + 1
start_summer <- which(Season == "Summer") ; end_summer <- start_summer + 1
start_autumn <- which(Season == "Autumn") ; end_autumn <- start_autumn + 1
start_winter <- which(Season == "Winter") ; end_winter <- start_winter + 1

# Indicate the size (y axis) of the rectangle
ymin_season <- rep(0, 24)
ymax_season <- rep(1, 24)

# Create a dataframe for indicating the position of the rectangles
shade <- data.frame (start_spring, end_spring, 
                     start_summer, end_summer, 
                     start_autumn, end_autumn, 
                     start_winter, end_winter, 
                     ymin_season, ymax_season)

# Plot
ggplot (df) +
  geom_line(aes(x=Iteration, y=Values)) + 
  geom_rect (data=shade, aes(xmin=start_spring, xmax=end_spring, ymin=ymin_season, ymax=ymax_season, fill="green"), alpha=0.05) +
  geom_rect (data=shade, aes(xmin=start_summer, xmax=end_summer, ymin=ymin_season, ymax=ymax_season, fill="red"), alpha=0.05) +
  geom_rect (data=shade, aes(xmin=start_autumn, xmax=end_autumn, ymin=ymin_season, ymax=ymax_season, fill="brown"), alpha=0.05) +
  geom_rect (data=shade, aes(xmin=start_winter, xmax=end_winter, ymin=ymin_season, ymax=ymax_season, fill="blue"), alpha=0.05)

0 个答案:

没有答案