我在為 ggplot 存盤 my_theme 時遇到問題。我想為我的 ggplot 有相同的主題,并為不同的 ggplot 靈活
# my plot is
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 code is
my_theme <- function(size=size, color=colour, angel=angle){
theme(plot.title = element_text(family ="serif", color = titles.colour,
face = "bold", size =plot.title.size),
axis.title.x = element_text(family = "serif", color = titles.colour,
size = 20),
axis.title.y = element_text(family = "serif", color = titles.colour,
size = 20),
axis.text.x = element_text(size = 10,angel=x.angle))
}
但這不適用于我的不同情節
# my different plot code
# Code you should be able to run without changing any of this code
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
# and this
# Code you should be able to run without changing any of this code
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熱心網友回復:
您正在將引數傳遞給您的函式沒有的引數,并在您的函式中使用不存在的變數。
您的函式可能有NULL默認值(因為 ggplot 在這種情況下使用回退默認值)。當你想在函式內部使用傳遞給函式的值時,你必須使用傳遞引數的名稱,就像它們在函式定義中一樣(你不能size在函式定義中使用并titles.size在函式內部使用,例如)
您的主題功能可能如下所示:
my_theme <- function(size = NULL, color = NULL, angle = NULL) {
theme(plot.title = element_text(family ="serif", color = color,
face = "bold", size = size),
axis.title.x = element_text(family = "serif", color = color,
size = 20),
axis.title.y = element_text(family = "serif", color = color,
size = 20),
axis.text.x = element_text(size = 10, angle = angle))
}
當你使用你的函式時,它必須與你在函式定義中輸入的名稱完全相同
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(color = "grey", size = 30, angle = -45)

默認值如下所示:
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()

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