分享

让你的ggplot2主题支持markdown和css

 阿越就是我 2023-10-12 发布于上海

简介

mdthemes包可以让你的ggplot2支持Markdown语法,和之前介绍的ggtext有异曲同工之妙啊!这个包其实也是基于ggtext包的,但是mdthemes更加强大!

安装

install.packages("mdthemes")

或者使用开发版:

if (!requireNamespace("remotes", quietly = TRUE)) {
  install.packages("remotes")
}
remotes::install_github("thomas-neitmann/mdthemes", upgrade = "never")

使用

目前mdthemes支持的主题非常多,已经支持以下R包的所有主题:ggplot2/ggthemes/hvbrthemes/tvthemes/cowplot。使用也是非常方便,只要在主题前加上md_即可!

library(ggplot2)
library(mdthemes)
data(mtcars)

p <- ggplot(mtcars, aes(hp, mpg)) +
  geom_point() +
  labs(
    title = "This is a **bold** title",
    subtitle = "And an *italics* subtitle",
    x = "**_hp_**",
    caption = "<span style = 'color:blue'>A blue caption</span>"
  )

p + theme_minimal()
p + md_theme_minimal()
p + ggthemes::theme_fivethirtyeight()
p + md_theme_fivethirtyeight()

改变样式小例子

data("diamonds")

p <- ggplot(diamonds, aes(x = cut, fill = cut)) + geom_bar() + 
  labs(title = "<span style = 'color:#93C1DE'>**Roche**</span> in <span style = 'color:darkorange'>**mtcars**</span>",
       caption = "Visiualized by <span style = 'color:#D52B1E'>**Ayue**</span>")
p + md_theme_minimal()

把其他主题变为支持markdown的主题

p + ggcharts::theme_hermit() # 默认不支持

使用as_md_theme变成支持markdown的主题!

p + as_md_theme(ggcharts::theme_hermit())

坐标轴标签添加不同颜色

library(tidyverse)

data("gapminder", package = "gapminder")
data(biomedicalrevenue, package = "ggcharts")

label <- function(x) {
  if (x %in% c("Roche""Novartis")) {
    paste0("<span style='color:#D52B1E'>**", x, "**</span>")
  } else {
    paste0("<span style='color:gray'>", x, "</span>")
  }
}

spec <- ggcharts::highlight_spec(
  what = c("Roche""Novartis"),
  highlight_color = "#D52B1E",
  other_color = "gray"
)
biomedicalrevenue %>%
  filter(year == 2018) %>%
  ggcharts::bar_chart(
    company,
    revenue,
    highlight = spec,
    top_n = 10
  ) +
  scale_x_discrete(labels = Vectorize(label)) +
  labs(
    x = NULL,
    y = "Revenue in 2018 (Billion USD)",
    title = glue::glue("Two {shiny::span('**Swiss**', style='color:#D52B1E')} Companies Are Among The Top 10 Big Pharma")
  ) +
  md_theme_minimal_vgrid() +
  theme(plot.title.position = "plot")
image-20220213152643879

是不是非常神奇,作者表示有你喜欢的ggplot2主题还未被mdthemes支持,你可以直接去Github提issue,作者很乐意帮你加上哦。

空一行

以上就是今天的内容,希望对你有帮助哦!欢迎点赞、在看、关注、转发

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多