I am plotting data with many variables using facets and would like to label the title of each facet using its variable however some variables have subscripts such as NO[3], SO[4].
I tried the following code but they turn out the same:
NewDat1$facets = factor(NewDat1$Parameter, labels = c( " Alkalinity",
"Ca (CaCO3)","Cl(mg/l),", "Conductivity (mS/m)","Cu (mg/l)","F (mg/l)",
"Fe (mg/l)","K (mg/l","Mg (CaCO3)"," Mn(mg/l)","Na (mg/l)",
expression("NO[3] (mg/l)"), "pH",expression (" SiO[2](mg/l)"),
expression("SO[4] (mg/l)"),"TDS (TDS Calculated)",
"Turbidity (NTU)","Zn (mg/l)"))
ggplot(na.omit(NewDat1), aes(Year, Value, color = Location))
geom_line()
geom_point()
facet_wrap(~facets, scales = "free_y" )
NewDat1 <- structure(list(Year = c(1998, 1999, 2000, 2001, 2002, 2003),
Value = c(8.06666666666667, 8.15, 8.3, 8.38333333333333,
8.05, 8.36666666666667), Parameter = c("pH", "pH", "pH",
"pH", "pH", "pH"), Location = c("Roshpinah", "Roshpinah",
"Roshpinah", "Roshpinah", "Roshpinah", "Roshpinah"), facets = structure(c(13L,
13L, 13L, 13L, 13L, 13L), .Label = c(" Alkalinity", "Ca (CaCO3)",
"Cl (mg/l),", "Conductivity (mS/m)", "Cu (mg/l)", "F (mg/l)",
"Fe (mg/l)", "K (mg/l", "Mg (CaCO3)", " Mn (mg/l)", "Na (mg/l)",
"NO[3] (mg/l)", "pH", " SiO[2] (mg/l)", "SO[4] (mg/l)", "TDS (TDS Calculated)",
"Turbidity (NTU)", "Zn (mg/l)"), class = "factor")), row.names = c(NA, -6L),
class = c("tbl_df", "tbl", "data.frame"))
Any suggestions on how to do this?
CodePudding user response:
Have all your factor labels as strings rather than expressions and use labeller = label_parsed
. Note that your sample data only contains a single level of the faceting variable, so I have had to fake the levels and use drop = FALSE
inside facet_grid
to show this in action:
NewDat1$facets = factor(NewDat1$Parameter, levels = c( "Alkalinity",
"Ca (CaCO3)",
"Cl(mg/l)",
"Conductivity (mS/m)",
"Cu (mg/l)",
"F (mg/l)",
"Fe (mg/l)",
"K (mg/l)",
"Mg (CaCO3)",
" Mn(mg/l)",
"Na (mg/l)",
"NO[3] (mg/l)",
"pH",
"SiO[2] (mg/l)",
"SO[4] (mg/l)",
"TDS (TDS~Calculated)",
"Turbidity (NTU)",
"Zn (mg/l)"))
ggplot(na.omit(NewDat1), aes(Year, Value, color = Location))
geom_line()
geom_point()
facet_wrap(~ facets, scales = "free_y", drop = FALSE,
labeller = label_parsed)