如何更改树形图标签的颜色和字体

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

我想将树状图最暗矩形上的标签颜色更改为白色以提高可读性。有没有办法做到这一点?我还想更改标签的字体。理想情况下,我希望字体与基本 R 默认字体相匹配(我不确定该字体叫什么?)。有没有办法改变标签字体?

# Creating Dataframe 
 subgroup <-c()
 df<- data.frame(Fruits=c("Owners' Equivalent Rent of Residences", 
                     "Rent of Primary Residence",
                     "New Vehicles", 
                    
    "Motor Vehicle Insurance",
                     "Motor Vehicle Maintenance and Repair",
                    
                     "Apparel", 
                     "Medical Care Commodities",
                     "Alcoholic Beverages", 
                     "Hospital Services",
                     "Tobacco and Smoking",
                     "Physicians Services",
                     "Gasoline All Types",
                     "Electricity", 
                    
                    
                     "Food Away From Home", 
                     "Meats Poultry Fish and Eggs", 
                     "Fruits and Vegetables", 
                     "Dairy and Related Products",
                     "Cereals And Bakery Products", 
                     "Other Foods at Home"), 
            perc=c(6.7, 6.9, 1.3, 19.2, 8.5, 1.1, 5, 2.9, 
                   6.3, 7.7, 0.7, -8.9, 3.4, 5.3, 0.1, 0.4, 
                   -1.4, 3.4, 3.3)) 
 library(ggplot2)
 library(treemapify)

 pal_fill <- colorRampPalette(scales::brewer_pal(palette = "Reds")(9))
 pal_fill <- pal_fill(length(unique(df$Fruits)))
 names(pal_fill) <- levels(reorder(df$Fruits, df$perc))

 ggplot(df, aes(area = perc, fill = Fruits, label = Fruits)) +
  geom_treemap(layout = "squarified") +
  geom_treemap_text(
   aes(label = paste0(Fruits, "\n", perc, "%")),
 place = "centre", size = 12
  ) +
 scale_fill_manual(values = pal_fill) +
 labs(title = "Categories Contributing Most to Inflation in 2023") +
 guides(fill = "none")
ggplot2 plotly rstudio
1个回答
0
投票

在更改字体系列的情况下,请查看

?graphics::par
family
参数的关系,其中提到了以下内容:

用于绘制文本的字体系列的名称。 ...默认值是“”,这意味着将使用默认的设备字体(这些字体应该在设备的帮助页面上列出)

因此,在基础 R 中,用于绘图和图形的默认字体取决于系统,因为它依赖于可用的标准字体和运行 R 的操作系统的默认设置。

根据您的操作系统,使用以下命令检查可用字体:

windowsFonts()
X11Fonts()
quartzFonts() 

在您的情况下,您可以使用

family
中的参数
treemapify::geom_treemap_text
ggplot2::element_text
内的参数
text
中的
ggplot2::theme
来更改字体系列。例如使用
serif
mono
:

ggplot(df, aes(area = perc, fill = Fruits, label = Fruits)) +
  geom_treemap(layout = "squarified") +
  geom_treemap_text(
    aes(label = paste0(Fruits, "\n", perc, "%")),
    place = "centre", size = 12, family = "serif"
  ) +
  scale_fill_manual(values = pal_fill) +
  labs(title = "Categories Contributing Most to Inflation in 2023") +
  guides(fill = "none") +
  theme(text = element_text(family = "mono"))

还有一个软件包

systemfonts
提供对字体目录的系统本机访问,使用功能
systemsfonts::system_fonts()
您可以获取系统上安装的字体。

要加载字体,您需要使用包

extrafont
。请参阅此处了解更多信息以开始使用该软件包。

例如,在您的情况下,我能够使用

Bahnschrift
Calibri
获得以下结果:

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