问题
The current documentation for theme element axis.text says:
axis.text
tick labels along axes (element_text; inherits from text)
but it seems like the inheritance isn't working.
This code gives the plot below, with axis text in grey.
library(ggplot2)
ggplot(data.frame(x=1:10, y=1:10), aes(x, y)) +
geom_point(color='red') +
theme(rect = element_rect(fill = 'black'),
line = element_line(color = 'white'),
text = element_text(color = 'blue'),
panel.background = element_blank())
Setting axis.text explicitly works, but I was expecting code snippet 1 to already produce this result
ggplot(data.frame(x=1:10, y=1:10), aes(x, y)) +
geom_point(color='red') +
theme(rect = element_rect(fill = 'black'),
line = element_line(color = 'white'),
text = element_text(color = 'blue'),
# *** setting this explictly ***
axis.text = element_text(color = 'blue'),
panel.background = element_blank())
I'm starting from a fresh R session, with this sessionInfo()
R version 3.3.1 (2016-06-21)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: OS X 10.11.6 (El Capitan)
locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] ggplot2_2.2.0
loaded via a namespace (and not attached):
[1] labeling_0.3 colorspace_1.2-6 scales_0.4.1 assertthat_0.1 lazyeval_0.2.0
[6] plyr_1.8.4 tools_3.3.1 gtable_0.2.0 tibble_1.1 Rcpp_0.12.6
[11] grid_3.3.1 munsell_0.4.3
How can I specify high-level theme elements and let those settings cascade down via inheritance? Do I need to somehow 'clear' the default theme?
回答1:
The difference is that your call to theme() in the first example results in an "incomplete" theme object.
Consider:
attr(theme(rect = element_rect(fill = 'black'),
line = element_line(colour = 'white'),
text = element_text(colour = 'blue'),
panel.background = element_blank()), "complete")
This should return FALSE. My understanding is that a call to theme() when the theme is incomplete does not have all of the inheritance. A theme like theme_grey() is complete and so inheritance works. I'm not 100% positive however, but this line in the documentation seems to suggest it.
The object returned by a call to a complete theme function is now a nested list of theme elements and their properties, which enables the new theming system to support inheritance of properties.
Look at this page, specifically the section called "Complete and incomplete theme objects". It discusses the same issues with color there, and shows you how to create your own [complete] custom theme where inheritance works.
来源:https://stackoverflow.com/questions/41006924/ggplot2-theme-axis-text-not-inheriting-from-text