Reputation: 95
for example I have dataset below:
df <- structure(list(Species = c("PM10", "Na+", "NH4+", "K+", "Mg2+", "Cl-",
"NO3-", "Oxalate", "MSA", "ssCa2+", "nssCa2+", "ssSO42-", "nssSO42-",
"Al", "Ti", "V", "Cr", "Mn", "Fe", "Ni", "Cu", "As", "Cd", "Ba",
"La", "Ce", "Pb"), Species_order = c(1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27), Secondary_conc = c(411.18, 3.432, 17.552, 2.4972,
0.64528, 0, 18.207, 3.2252, 0, 0.023608, 3.3337, 0.13273, 54.707,
0.7192, 0.029855, 1.7612e-05, 0, 0.024012, 1.5637, 0, 0.026486,
0, 0, 0, 1.1561e-06, 4.6873e-06, 6.0361e-06), Secondary_perc = c(16.35872,
1.506537, 33.72603, 19.34941, 2.373839, 0, 68.52145, 88.5679,
0, 0.2825614, 34.85788, 0.241084, 26.63269, 7.877051, 7.609215,
0.09306203, 0, 12.60384, 12.5355, 0, 34.27987, 0, 0, 0, 0.01647077,
0.03159252, 0.005472207)), row.names = c(NA, -27L), class = c("tbl_df",
"tbl", "data.frame"))
I would like to plot Species column as x-axis, Secondary_conc column as primary y-axis with bar chart in log scale, and Secondary_perc as secondary y-axis with point chart by using ggplot. For those reason I use below code:
library(tidyr)
library(dplyr)
library(ggplot2)
library(scales)
theme_set(theme_bw())
ggplot(df) +
geom_bar(aes(x=reorder(Species,Species_order), y=Secondary_conc),
stat = 'identity',fill="cadetblue2") +
scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x),
labels = trans_format("log10", math_format(10^.x))) +
geom_point(aes(x=reorder(Species,Species_order), y=Secondary_perc/0.25, color="red")) +
scale_y_continuous(expression(bold(Concentration~(ng/m^{3}))), sec.axis = sec_axis(~.*0.25, name = "%" ))+
theme(axis.title.y = element_text (face="bold", size=8),
axis.text.x = element_text(face = "bold",size = 8, angle = -45),
legend.position = "none") +
labs(x=NULL)
However, I got error message: Scale for 'y' is already present. Adding another scale for 'y', which will replace the existing scale. and the scale for primary y-axis is not in log scale.
Anybody know how to overcome this and change primary y-axis as log scale? Thank you.
Upvotes: 0
Views: 64
Reputation: 174348
I would probably just handle the transformations myself here via arithmetic in aes
, reversed in the breaks
and labels
arguments of scale_y_continuous
ggplot(df, aes(x = reorder(Species,Species_order))) +
geom_col(aes(y = log10(Secondary_conc) + 6, fill = 'concentration')) +
geom_point(aes(y = Secondary_perc * 0.1, color = "percentage")) +
scale_y_continuous(expression(bold(Concentration~(ng/m^{3}))),
breaks = 0:9, labels = ~10^(.x - 6),
sec.axis = sec_axis(~.*10, name = "%" )) +
scale_fill_manual(values = 'cadetblue') +
scale_color_manual(values = 'red') +
theme(axis.title.y = element_text (face="bold", size=8),
axis.text.x = element_text(face = "bold",size = 8, angle = -45),
legend.position = 'bottom') +
labs(x = NULL, fill = NULL, color = NULL)
Upvotes: 0