R 绘图 – 中文支持

以下是在 R 语言中绘制图表时实现中文支持的中文讲解,结合 Visual Studio Code(VSCode)环境,重点解决中文显示问题(如乱码)并提供饼图和条形图的示例。内容简洁清晰,适合初学者。

1. R 中文支持简介

R 语言在绘制图表(如饼图、条形图)时,默认可能不支持中文字符,导致标题、标签等出现乱码。macOS 系统上,中文支持需要正确配置字体和图形设备,以确保中文正常显示。VSCode 配合 R 扩展和 httpgd 包可优化中文图表的显示效果。

2. 准备工作

  • 确保 R 已安装:参考前述 macOS R 环境安装指南,确保 R 和 VSCode 配置完成。
  • 安装必要包
  • 基础绘图使用 R 自带的 pie()barplot() 函数。
  • 高级绘图推荐使用 ggplot2
    R install.packages("ggplot2")
  • 安装 httpgd 包以在 VSCode 中显示图形:
    R install.packages("httpgd")
  • VSCode 配置
  • 确保安装了 R 扩展和 languageserver(见前述指南)。
  • 在 VSCode 设置中启用 httpgd
    json { "r.plot.useHttpgd": true }
  • 安装 XQuartz(若需要):macOS 默认图形设备可能需要 XQuartz 支持中文显示:
  brew install --cask xquartz

3. 配置中文支持

R 在 macOS 上可能因字体或图形设备问题导致中文乱码。以下是解决方法:

方法 1:设置中文字体(基础绘图)

  1. 检查系统可用字体:
   quartzFonts()  # 查看 macOS 默认字体

常用中文字体包括 Arial Unicode MSSTHeitiPingFang SC

  1. 设置默认字体:
   par(family = "Arial Unicode MS")  # 或 "PingFang SC"

将此代码放在绘图代码之前,确保标题、标签使用中文字体。

方法 2:使用 httpgd(推荐)

httpgd 包通过浏览器渲染图形,支持中文显示,且与 VSCode 集成良好:

  1. 确保已安装 httpgd(见上)。
  2. 在 VSCode 的 settings.json 中启用:
   { "r.plot.useHttpgd": true }
  1. 绘图时自动使用 httpgd 设备,无需额外设置字体。

方法 3:使用 showtext

showtext 包简化中文字体管理,支持自定义字体:

  1. 安装并加载:
   install.packages("showtext")
   library(showtext)
   showtext_auto()  # 自动启用 showtext
  1. 指定中文字体:
   font_add("myfont", regular = "Arial Unicode MS")  # 或其他字体
   showtext_auto(family = "myfont")

4. 绘制饼图(支持中文)

以下是使用 pie()ggplot2 绘制饼图的示例,确保中文显示正常。

基础饼图(pie()

在 VSCode 中新建 .R 文件(如 pie_chart.R),输入:

# 设置中文字体
par(family = "Arial Unicode MS")

# 示例数据
categories <- c("苹果", "香蕉", "橙子", "葡萄")
values <- c(30, 25, 20, 15)

# 绘制饼图
pie(values, labels = paste0(categories, " (", round(values/sum(values)*100, 1), "%)"), 
    main = "水果销量占比", col = c("red", "yellow", "orange", "purple"))

高级饼图(ggplot2 + showtext

library(ggplot2)
library(showtext)
showtext_auto()  # 启用 showtext
font_add("myfont", regular = "Arial Unicode MS")  # 设置字体

# 创建数据框
data <- data.frame(
  category = c("苹果", "香蕉", "橙子", "葡萄"),
  value = c(30, 25, 20, 15)
)

# 绘制饼图
ggplot(data, aes(x = "", y = value, fill = category)) +
  geom_bar(stat = "identity", width = 0.4) +
  coord_polar("y") +
  theme_void() +
  geom_text(aes(label = paste0(round(value/sum(value)*100, 1), "%")), 
            position = position_stack(vjust = 0.5), family = "myfont") +
  labs(title = "水果销量占比") +
  scale_fill_manual(values = c("red", "yellow", "orange", "purple"))

运行代码

  1. 选中代码,按 Ctrl + Enter(或 Cmd + Enter)运行。
  2. 图形将在 VSCode 的“绘图”面板或浏览器中显示(若启用 httpgd)。

5. 绘制条形图(支持中文)

以下是使用 barplot()ggplot2 绘制条形图的示例。

基础条形图(barplot()

# 设置中文字体
par(family = "Arial Unicode MS")

# 示例数据
categories <- c("苹果", "香蕉", "橙子", "葡萄")
values <- c(30, 25, 20, 15)

# 绘制垂直条形图
barplot(values, names.arg = categories, main = "水果销量", xlab = "水果", ylab = "销量", 
        col = c("red", "yellow", "orange", "purple"))

高级条形图(ggplot2 + showtext

library(ggplot2)
library(showtext)
showtext_auto()
font_add("myfont", regular = "Arial Unicode MS")

# 创建数据框
data <- data.frame(
  category = c("苹果", "香蕉", "橙子", "葡萄"),
  value = c(30, 25, 20, 15)
)

# 绘制条形图
ggplot(data, aes(x = category, y = value, fill = category)) +
  geom_bar(stat = "identity") +
  geom_text(aes(label = value), vjust = -0.5, family = "myfont") +
  labs(title = "水果销量", x = "水果", y = "销量") +
  scale_fill_manual(values = c("red", "yellow", "orange", "purple")) +
  theme_minimal(base_family = "myfont")

6. 生成条形图(参考)

以下是基于示例数据的条形图代码块,用于 VSCode 显示:

{
  "type": "bar",
  "data": {
    "labels": ["苹果", "香蕉", "橙子", "葡萄"],
    "datasets": [{
      "label": "销量",
      "data": [30, 25, 20, 15],
      "backgroundColor": ["#FF0000", "#FFFF00", "#FFA500", "#800080"],
      "borderColor": ["#333333"],
      "borderWidth": 1
    }]
  },
  "options": {
    "scales": {
      "y": {
        "beginAtZero": true,
        "title": { "display": true, "text": "销量", "color": "#333333" }
      },
      "x": {
        "title": { "display": true, "text": "水果", "color": "#333333" }
      }
    },
    "plugins": {
      "title": {
        "display": true,
        "text": "水果销量",
        "color": "#333333"
      },
      "legend": {
        "display": false
      }
    }
  }
}

说明

  • 上述代码块模拟条形图效果,数据与 R 示例一致。
  • 实际 R 绘图使用 barplot()ggplot2,此图为参考。

7. 常见问题及解决

  • 中文乱码
  • 使用 par(family = "Arial Unicode MS")showtext 设置字体。
  • 确保安装 XQuartz(brew install --cask xquartz)。
  • 检查系统字体:运行 system("fc-list :lang=zh") 查看可用中文字体。
  • 图形不显示:确保 httpgd 已安装并启用 r.plot.useHttpgd。重启 VSCode 或检查图形设备:
  dev.list()  # 查看当前图形设备
  dev.off()   # 关闭设备重试
  • 字体不可用:若 Arial Unicode MS 无效,尝试 PingFang SCSTHeiti
  par(family = "PingFang SC")
  • 保存图形含乱码
  • 使用 png()pdf() 保存:
    R png("chart.png", family = "Arial Unicode MS") barplot(values, names.arg = categories, main = "水果销量") dev.off()
  • ggplot2 使用 ggsave()
    R ggsave("chart_ggplot.png", width = 6, height = 4, device = cairo_pdf)

8. 获取途径

  • R 语言:免费下载,访问 cran.r-project.org
  • VSCode:可通过 grok.comx.com、VSCode iOS/Android 应用免费使用(有限额)。付费订阅(如 SuperGrok)提供更高配额,详情见 x.ai/grok.

如需更复杂图表(如分组条形图、堆叠图)或特定中文数据绘图帮助,请提供数据或需求!

类似文章

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注