Jak używać przezroczystego tła w ggplot2
Możesz użyć następującej składni, aby utworzyć przezroczyste tło na wykresie w ggplot2:
p+ theme( panel. background = element_rect(fill=' transparent '), #transparent panel bg plot. background = element_rect(fill=' transparent ', color= NA ), #transparent plot bg panel. grid . major = element_blank(), #remove major gridlines panel. grid . minor = element_blank(), #remove minor gridlines legend. background = element_rect(fill=' transparent '), #transparent legend bg legend. box . background = element_rect(fill=' transparent ') #transparent legend panel )
Jeśli zdecydujesz się wyeksportować wykres za pomocą ggsave() , pamiętaj o określeniu, że tło powinno być przezroczyste:
ggsave(' myplot.png ' , p, bg = ' transparent ' )
Poniższy przykład pokazuje, jak zastosować tę składnię w praktyce.
Przykład: użycie przezroczystego tła w ggplot2
Poniższy kod pokazuje, jak utworzyć prosty zgrupowany wykres skrzynkowy w ggplot2:
library (ggplot2) #make this example reproducible set. seeds (1) #create dataset data <- data. frame (team=rep(c(' A ', ' B ', ' C '), each= 50 ), program=rep(c(' low ', ' high '), each= 25 ), values=seq(1:150)+sample(1:100, 150, replace= TRUE )) #create boxplot ggplot(data, aes (x=team, y=values, fill=program)) + geom_boxplot()
Aby stworzyć przezroczyste tło dla fabuły, możemy użyć poniższego kodu:
library (ggplot2) #make this example reproducible set. seeds (1) #create dataset data <- data. frame (team=rep(c(' A ', ' B ', ' C '), each= 50 ), program=rep(c(' low ', ' high '), each= 25 ), values=seq(1:150)+sample(1:100, 150, replace= TRUE )) #create boxplot p <- ggplot(data, aes (x=team, y=values, fill=program)) + geom_boxplot() + theme( panel. background = element_rect(fill=' transparent '), plot. background = element_rect(fill=' transparent ', color= NA ), panel. grid . major = element_blank(), panel. grid . minor = element_blank(), legend. background = element_rect(fill=' transparent '), legend. box . background = element_rect(fill=' transparent ') ) #display boxplot p
Możemy następnie wyeksportować tę ścieżkę do pliku PNG, określając, że tło w eksportowanym obrazie musi być przezroczyste:
ggsave(' grouped_boxplot.png ' , p, bg = ' transparent ' )
Jeśli otworzę ten wyeksportowany plik na swoim komputerze, widzę, że tło jest przezroczyste:
Dodatkowe zasoby
Jak zmienić rozmiar czcionki w ggplot2
Jak usunąć legendę w ggplot2
Jak usunąć linie siatki w ggplot2