R Studio中DT包生成的数据表默认显示Times New Roman字体的修改方案及默认字体原因咨询
R Studio中DT包生成的数据表默认显示Times New Roman字体的修改方案及默认字体原因咨询
嗨,我来帮你搞定这个DT表格字体的问题,顺便聊聊为啥Viewer默认会显示Times New Roman~
一、给DT表格单独设置字体(最直接的方案)
你之前试CSS没生效,大概率是写法不够全面,DT的表格结构有多层,得确保CSS能覆盖到所有元素。试试下面两种方法:
方法1:通过initComplete注入全局CSS
在datatable的options里加一段JS代码,初始化完成后给表格相关元素设置字体,这样不管是Viewer还是浏览器弹出窗口都会生效:
library(DT) summary <- read.csv('sample.csv') DT::datatable(summary, extensions = 'Buttons', options = list( autoWidth = TRUE, pageLength = 10, dom = 'Bfrtip', buttons = c('copy', 'csv', 'excel', 'pdf', 'print'), # 初始化完成后设置字体 initComplete = JS( "function(settings, json) {", // 给表格容器、筛选器、按钮等所有相关元素设置字体 "$('.dataTables_wrapper, .dataTables_filter, .dataTables_length, .dt-buttons').css({'font-family': 'Arial, sans-serif'});", "$('table.dataTable').css({'font-family': 'Arial, sans-serif'});", "}" ) ), filter = list( position = 'top', clear = FALSE))
方法2:用formatStyle统一设置列字体
如果只想针对表格内容设置,也可以用DT的formatStyle函数:
DT::datatable(summary, extensions = 'Buttons', options = list( autoWidth = TRUE, pageLength = 10, dom = 'Bfrtip', buttons = c('copy', 'csv', 'excel', 'pdf', 'print')), filter = list(position = 'top', clear = FALSE)) %>% formatStyle(columns = colnames(summary), fontFamily = 'Arial, sans-serif')
二、修改RStudio Viewer的全局字体(一劳永逸)
如果想让Viewer里所有内容都用Arial,不用每次给DT单独设置,可以修改RStudio的自定义样式表:
- 找到RStudio的样式表路径:
- Windows:
%APPDATA%\RStudio\styles\custom.css - Mac:
~/Library/Application Support/rstudio/styles/custom.css - Linux:
~/.config/rstudio/styles/custom.css
- Windows:
- 如果没有
custom.css文件就新建一个,添加下面的CSS代码:
/* 覆盖Viewer的全局字体 */ body { font-family: 'Arial', sans-serif !important; } /* 确保DT表格的字体也被覆盖 */ .dataTables_wrapper, table.dataTable { font-family: 'Arial', sans-serif !important; }
- 重启RStudio,之后Viewer里的所有网页内容(包括DT表格)都会用Arial显示啦。
三、为啥Viewer默认显示Times New Roman?
其实原因很简单:
- DT包生成的表格是HTML格式,RStudio Viewer本质是个内置浏览器,它的默认**衬线字体(serif)**在Windows系统里就是Times New Roman;
- DT的默认CSS没有强制指定无衬线字体,所以就继承了浏览器的默认衬线字体;
- 而ggplot的Plot面板是RStudio直接渲染的图形,它用的是系统默认的无衬线字体(比如Arial),所以两者看起来不一样。
备注:内容来源于stack exchange,提问作者aholtz
相关产品推荐
相关产品推荐

