Modifying fonts in ggplot2

前端 未结 7 1315
再見小時候
再見小時候 2020-11-29 16:43

I am looking for a way to modify font types in ggplot. At the moment I would be happy enough to simply change fonts to the \'courier\' font family, but ultimately my goal is

相关标签:
7条回答
  • 2020-11-29 17:46

    Sorted out my query with fairly minimal hassle. It was a two-step solution that I wouldn't have arrived at without following the advice of the members who responded.

    To change the ggplot text defaults, I adapted the code that Brandon referred me to at:

    http://johndunavent.com/combined-line-and-bar-chart-ggplot2

    Where John Dunavent creates a function, theme_min, that can be edited to provide the default options for a ggplot, including using fonts imported from Windows with the windowsFonts command. My adaptation of his code looks like this:

    theme_min = function (size=10, font=NA, face='plain', 
        panelColor=backgroundColor, axisColor='#999999', 
        gridColor=gridLinesColor, textColor='black') 
    {
        theme_text = function(...)
            ggplot2::theme_text(family=font, face=face, colour=textColor, 
                size=size, ...)
    
    opts(
        axis.text.x = theme_text(),
        axis.text.y = theme_text(),
        axis.line = theme_blank(),
        axis.ticks = theme_segment(colour=axisColor, size=0.25),
        panel.border = theme_rect(colour=backgroundColor),
        legend.background = theme_blank(),
        legend.key = theme_blank(),
        legend.key.size = unit(1.5, 'lines'),
        legend.text = theme_text(hjust=0),
        legend.title = theme_text(hjust=0),
        panel.background = theme_rect(fill=panelColor, colour=NA),
        panel.grid.major = theme_line(colour=gridColor, size=0.33),
        panel.grid.minor = theme_blank(),
        strip.background = theme_rect(fill=NA, colour=NA),
        strip.text.x = theme_text(hjust=0),
        strip.text.y = theme_text(angle=-90),
        plot.title = theme_text(hjust=0),
        plot.margin = unit(c(0.1, 0.1, 0.1, 0.1), 'lines'))
    }
    
    ##Create a custom font type. Could be 'F', 'TEST', whatever
    windowsFonts(F = windowsFont('Wide Latin'))
    
    ##and insert this line of code into the original code I list above: 
    + theme_min(font='F', size=10) 
    

    Awkwardly, there is no way (that I found) to generically modify the font settings for geom_text objects before a plot is created. James' solution above worked perfectly for this, though. Instead of using a standard font, I set fontfamily="F" to bring in the custom font that I selected in theme_min(), i.e.:

    grid.gedit("GRID.text",gp=gpar(fontfamily="F"))
    

    Hopefully this is useful to any other users looking to modify fonts on their graphs.

    Cheers to all who helped me sort this out! Aaron

    0 讨论(0)
提交回复
热议问题