I have multiple datasets that need to be run through a single graphing function to produce a set of graphs. The datasets contain measurements from two Instruments "G"
and "H"
. Each Instrument
is either placed in the "Up"
or "Down"
position, which changes across the datasets. Right now I am trying to solidify the code before putting it in a function.
I need to assign the same color to the same Position
in every graph, and need to label the series with both the Instrument
and Position
. So "Position" == "Up & "Instrument" == "G"
and "Position" == "Up" & "Instrument" == "H"
need the same color. I would like to use the wesanderson
package, "Cavalcanti1"
palette, colors 2 and 3. Position
"Up"
as color 2 and Position
"Down"
as color 3.
This Question and This Question are almost helpful, but my series names change with every dataset. I thought using regular expression to identify "Up"
or "Down"
strings in the legend_title
column in a term like scale_color_manual(values = c("foo" = "#999999", "bar" = "#E69F00"))
might be a solution, but I keep getting errors in my graphing code.
I am just starting to learn more about regular expression. Can you use it outside of regular expression functions like grep()? Or does scale_color_manual() accept that syntax to assign specific colors to values? Any thoughts or suggestions are appreciated!
Here is a simplified version of my data and code:
library(dplyr)
library(ggplot2)
library(hms)
library(wesanderson) # color palette I want to use
df1 <- data.frame(Time = as.hms(c("11:30:00", "11:30:30", "11:31:00", "11:30:00", "11:30:30", "11:31:00")),
Chl = c(3.1,3.6,4,2.2,2,1.8),
Instrument = c('H','H','H','G','G','G'),
Position = c('Up','Up','Up','Down','Down','Down'))
df1$Instrument <- as.character(df1$Instrument) #to mimic my actual data
df1$Position <- as.character(df1$Position)
df2 <- data.frame(Time = as.hms(c("09:30:00", "09:30:30", "09:31:00", "09:30:00", "09:30:30", "09:31:00")),
Chl = c(3.0,3.5,3.7,1.5,1.3,1.0),
Instrument = c('H','H','H','G','G','G'),
Position = c('Down','Down','Down','Up','Up','Up'))
df2$Instrument <- as.character(df2$Instrument)#to mimic my actual data
df2$Position <- as.character(df2$Position)
### test code chunks for function. Paste in df1 or df2
modify_df <- df2 %>%
mutate(legend_title = paste0(Position, ' ', Instrument))
# Create column with desired series names/labels
(one_plot = ggplot(data = modify_df, aes(x = Time, y = Chl, color = legend_title)) +
geom_line(size = .5) +
scale_color_manual(values = c("^Down" = wes_palette("Cavalcanti1")[3],
"^Up" = wes_palette("Cavalcanti1")[2])) + # regular expression to look for Up or Down at the beginning of the text
theme(axis.text.x = element_text(angle = 45, hjust = 1),
legend.title = element_blank()) +
labs(x = ""))