自定义插入 ggplot 中的表格外观

问题描述 投票:0回答:1

我想用指定的主题将表格注释到现有的 ggplot 中。 但是,我想调整表格的外观并更改网格线的颜色和表格标题的背景颜色。到目前为止,我设法更改了表格的背景颜色,但没有更改其他颜色。这要怎么修改。

这是一个小工作示例:

# Creating a sample data frame
df <- data.frame(
  x = 1:10,
  y = rnorm(10)
)

# Creating a plot
p <- ggplot(df, aes(x, y)) +
  geom_point() +
  labs(title = "Scatter Plot Example", x = "X-axis", y = "Y-axis")+
  theme_bw()

# Creating a table legend
legend_table <- tibble(x = 5, y = 0,
                       tb = list(data.frame(  Category = c("A", "B", "C"),
                                              Value = c(10, 20, 30))))

# Adding a table as a legend using annotate
p + geom_table(data = legend_table,   aes(x = x, y = y, label = tb),
               color = "red", fill = "#FFCCCC",
               vjust = 1)
r ggplot2 annotate
1个回答
0
投票
# change the color of the gridlines 
# change the background color of the table header

# So far I managed to change the background color of the table but not other colors. How can this be modified.


library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.3.2
library(tibble)
library(ggpmisc)
#> Loading required package: ggpp
#> 
#> Attaching package: 'ggpp'
#> The following object is masked from 'package:ggplot2':
#> 
#>     annotate
#> Registered S3 method overwritten by 'ggpmisc':
#>   method                  from   
#>   as.character.polynomial polynom
library(gridExtra)

# Creating a sample data frame
df <- data.frame(
  x = 1:10,
  y = rnorm(10)
)

# Creating a plot
p <- ggplot(df, aes(x, y)) +
  geom_point() +
  labs(title = "Scatter Plot Example", x = "X-axis", y = "Y-axis")+
  theme_bw()

# Creating a table legend
legend_table <- tibble(x = 5, y = 0,
                       tb = list(data.frame(  Category = c("A", "B", "C"),
                                              Value = c(10, 20, 30))))

# create your own table theme with `gridExtra::ttheme_default()`
# I had to look into the function to determine the arguments to adjust

my_ttheme <- 
  gridExtra::ttheme_default(colhead = list(fg_params=list(col="white"),
                                           bg_params=list(fill="red")),
                            core = list(bg_params=list(fill = "#FFCCCC", col = "green")))

p + geom_table(data = legend_table,   aes(x = x, y = y, label = tb),
               vjust = 1,
               table.theme = my_ttheme)

创建于 2023-11-16,使用 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.