簡體   English   中英

r 中 ggplot2 的主題

[英]Theme for ggplot2 in r

我找到了一些 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))

我想創建一個自定義 function (my_theme),它具有圖形代碼的所有主題信息(如上圖),但是這個 function 應該允許我調整 plot 標題的大小以及數字的角度x 軸。 最后,我應該能夠將所有標題(即 plot、x 軸和 y 軸標題)從一種顏色更改為另一種顏色。 默認情況下,plot 標題的大小應為 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 arguments

還有這段代碼

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

首先定義一個function,其中需要更改的元素為arguments。將那些arguments設置為您真正喜歡的圖形中的默認值。 要更改默認值,請在其調用中將它們傳遞給 function。

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 package (v2.0.1) 創建於 2022-03-28

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM