我找到了一些 ggplot2 圖表的代碼,它非常喜歡:
ggplot(subset(diamonds, diamonds$color == "E"))
geom_point(aes(carat, price), size = 2)
scale_y_continuous("Price ($)")
scale_x_continuous("Carat")
ggtitle("Colourless E Diamonds")
theme(plot.title = element_text(family ="serif", color = "black",
face = "bold", size = 20),
axis.title.x = element_text(family = "serif", color = "black",
size = 20),
axis.title.y = element_text(family = "serif", color = "black",
size = 20),
axis.text.x = element_text(size = 10))
我想創建一個自定義函式(my_theme),其中包含圖形代碼的所有主題資訊,如(上圖),但這個函式應該允許我調整繪圖示題的大小以及數字的角度x 軸。最后,我應該能夠將所有標題(即繪圖、x 軸和 y 軸標題)從一種顏色更改為另一種顏色。默認情況下,繪圖示題的大小應為 20,x 軸角度為 0,所有標題的顏色為黑色。我寫了這些代碼,但我收到了錯誤。我需要適用于不同代碼的靈活代碼,例如
ggplot(subset(diamonds, diamonds$color == "E"))
geom_point(aes(carat, price), size = 2)
scale_y_continuous("Price ($)")
scale_x_continuous("Carat")
ggtitle("Colourless E Diamonds")
my_theme(titles.colour = "grey", plot.title.size = 30, x.angle = -45) # should be able to take these arguements
還有這段代碼
ggplot(subset(diamonds, diamonds$color == "E"))
geom_point(aes(carat, price), size = 2)
scale_y_continuous("Price ($)")
scale_x_continuous("Carat")
ggtitle("Colourless E Diamonds")
my_theme() #should have defaults
uj5u.com熱心網友回復:
首先定義一個函式,將需要更改的元素作為引數。在您真正喜歡的圖表中將這些引數設定為默認值。要更改默認值,請將它們傳遞給其呼叫中的函式。
library(ggplot2)
my_theme <- function(plot_title_size = 30, colour = "black", size = 20, angle= 0){
theme(plot.title = element_text(family ="serif",
face = "bold",
colour = colour,
size = plot_title_size),
axis.title.x = element_text(family = "serif",
colour = colour,
size = size),
axis.title.y = element_text(family = "serif",
colour = colour,
size = size),
axis.text.x = element_text(size = 10, angle = angle, vjust = 0.5))
}
ggplot(subset(diamonds, color == "E"), aes(carat, price))
geom_point(size = 2)
scale_y_continuous("Price ($)")
scale_x_continuous("Carat")
ggtitle("Colourless E Diamonds")
geom_smooth(formula = y ~ x,method=lm,se=FALSE)
my_theme()

ggplot(subset(diamonds, color == "E"), aes(carat, price))
geom_point(size = 2)
scale_y_continuous("Price ($)")
scale_x_continuous("Carat")
ggtitle("Colourless E Diamonds")
geom_smooth(formula = y ~ x,method=lm,se=FALSE)
my_theme(colour = "grey30", angle = 45)

由reprex 包創建于 2022-03-28 (v2.0.1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/452357.html
