首页 > 解决方案 > 在 R 的调色板中保存颜色

问题描述

我想保存自动 ggplot 函数分配给绘图中每个站点的颜色。我想将分配给每个站点的颜色保存在调色板中,以便在其他绘图中再次重复使用:

ggplot(DSF_moments, aes(x=year, y=max, group = station, colour = station)) + 
  geom_line(size = 1)  + 
  geom_point(size=1.5, shape=21, fill="white") + 
  labs(y ="Annual max flow [m3/s]", x = "year", title = "Annual Maximum Streamflow", size = 50) +
  theme(plot.title = element_text(size=16), axis.text.y = element_text(size=11), axis.text.x = element_text(angle = 90, size=11)) + scale_x_continuous (breaks=seq(min(DSF_moments$year),max(DSF_moments$year),by=2)) +
  scale_y_continuous (breaks=seq(min(DSF_moments$max),max(DSF_moments$max),by=5000))
dev.copy(png,"Plot_Max_Annual_RawData.png",width=22,height=11,units="in",res=100)
dev.off()

使用上面代码中的颜色函数,ggplot为每个站分配一个颜色,我不想改变颜色,我只想知道每个站分配哪种颜色。这个想法是在为每个站点单独生成一个绘图后,但保持先前在第一个公共绘图中分配给所有站点的颜色。

for (i in 1:length(listDF2)) 
{
  df1 <- as.data.frame(listDF2[[i]])
  df1[is.na(df1)] <- 0
  temp_plot <- ggplot(df1, aes(x = day, y = DailyMeanStreamflow, colour=Station[i])) +
  geom_line(size = 1)  + 
  geom_point(size=1.5, shape=21, fill="white") + 
  facet_wrap(~ month, ncol = 3) +
  labs(title = "Daily Mean Streamflow",
       subtitle = "Data plotted by month",
       y = "Daily Mean Streamflow [m3/s]", x="Days") + 
  scale_x_continuous (breaks=seq(1,max(df1$day),by=1)) + theme(axis.text.x = element_text(size=9))

  print(temp_plot)

  name4<- paste("DailyStreamflow_byMonth","_", siteNumber[i], ".png", sep="")
  ggsave(temp_plot,filename = name4,width=22,height=11,units="in",dpi=500)
  dev.off()
}

我现在想为每个图表分配之前分配的颜色。如何将 ggplot 分配的默认颜色保存到每个站点?

站的格式为 chr:“094985005”、“09498501”、“09489500”

标签: rggplot2colorspalette

解决方案


评论中链接的答案包含大量重要信息,我在这里展示的内容就是基于此。

# Generate the colors 
stations = unique(DSF_moments$station)
station_cols = scales::hue_pal()(length(stations))
# Assign them alphabetically (ggplot's default, which you don't seem to modify) names(station_cols) = sort(stations)

# use these colors for (some) of these stations in a plot with 
scale_color_manual(values = station_cols)

由于您尚未共享任何数据,因此未经测试,但它至少应该让您非常接近。如果您需要更多帮助,请分享一个可重现的示例。


推荐阅读