如何在 lapply 中设置 ggplot 的日期轴语言?

问题描述

我在更改 ggplot 日期轴的语言时遇到问题。通常,我只会使用 Sys.setlocale() 然后创建情节。现在我已经创建了一个函数来完成这个(在其他布局特定的更改中)并且它工作得很好。但是,当我在 lapply() 中使用此函数时,它不再起作用。这真的让我很困惑。有没有其他方法可以在 ggplot 中设置日期轴语言?

这是一个最小的可复制示例:(我在 Windows 上工作,因此其他人可能需要更改 localeSys.setlocale() 中的 ggtheme() 参数)

library( ggplot2 )

# sample data 
df <- data.frame( "Date" = as.Date( c( "2021-04-01","2021-04-20","2021-05-07","2021-05-25" ) ),"Value" = c( 1,2,3,4 ) )

# function to change Date-axis language
ggtheme <- function( plot,language ){
  
  switch( language,"EN" = Sys.setlocale( category = "LC_ALL",locale = "english" ),"DE" = Sys.setlocale( category = "LC_ALL",locale = "german" ),Sys.setlocale( category = "LC_ALL",locale = "english" ) )
  
  plot <- plot
  
  return( plot )
  
}

# check current locale (just as information)
Sys.getlocale()

# lapply to create plots with english and german x-axis (date) labels
ls_plots <- lapply( c( "DE","EN" ),function( LANGUAGE ){
  
  plot <- ggplot( df,aes( x = Date,y = Value ) ) +
    geom_line() +
    ggtitle( paste( "Here x-axis should be in",LANGUAGE ) )
  
  plot <- ggtheme( plot,language = LANGUAGE )
  
  return( plot )
  
})

names( ls_plots ) <- c( "DE","EN" )

# output (for DE it should be Mai; for EN it should be May)
ls_plots$DE
ls_plots$EN

任何帮助将不胜感激!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)