首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在R中并排绘制几组箱形图

在 R 中,可以采用 ggplot2 包来绘制箱形图。通过使用 ggplot() 函数,可以创建一个包含多个箱形图的布局。例如,以下代码将创建一个包含两列的箱形图,其中第一列有 3 个箱形图,第二列有 2 个箱形图:

代码语言:txt
复制
ggplot(data = df, aes(x = loc, y = cars_sold)) +
  geom_boxplot(fill = "darkblue", color = "white") +
  coord_flip() +
  labs(title = "Number of Cars Sold by Dealership") +
  facet_wrap(~V1, labeller = labeller(.rows = NULL, .cols = NULL)) +
  theme_bw() +
  theme(panel.border = element_blank(), panel.grid = element_blank(), strip.text = element_blank())

在上面的代码中,df 是数据框,loc 是地点变量,cars_sold 是汽车销售量变量。ggplot() 函数使用 aes() 函数指定 x 轴和 y 轴的变量,并使用 geom_boxplot() 函数来绘制箱形图。coord_flip() 函数将坐标轴翻转,以便在面板中正确显示数据。labs() 函数用于设置图例的标题和坐标轴的标签。facet_wrap() 函数用于将图分成多个面板,这里我们使用 .rows.cols 参数来指定面板的行数和列数。theme_bw() 函数用于设置主题的黑色背景。theme() 函数用于设置面板的边框、网格和文字样式。

如果您需要绘制多组箱形图,可以采用 facet_wrap() 函数,并根据需要设置不同的参数。例如,以下代码将创建一个包含三组箱形图的图,每组箱形图都包含 3 个箱形图:

代码语言:txt
复制
ggplot(data = df, aes(x = loc, y = cars_sold)) +
  geom_boxplot(fill = "darkblue", color = "white") +
  coord_flip() +
  labs(title = "Number of Cars Sold by Dealership") +
  facet_wrap(~V1, labeller = labeller(.rows = NULL, .cols = NULL), strip.text = element_blank()) +
  theme_bw()

在上面的代码中,我们使用 facet_wrap() 函数将图分成三组面板,并使用 .rows.cols 参数指定每组面板的行数和列数。我们还使用 strip.text 参数来删除每组面板中的文本。

最后,我们可以使用 ggplotly() 函数将 ggplot 图转换为 Plotly 图,以便在 Web 浏览器中显示。例如,以下代码将创建一个包含三组箱形图的图,并在 Web 浏览器中显示:

代码语言:txt
复制
ggplot(data = df, aes(x = loc, y = cars_sold)) +
  geom_boxplot(fill = "darkblue", color = "white") +
  coord_flip() +
  labs(title = "Number of Cars Sold by Dealership") +
  facet_wrap(~V1, labeller = labeller(.rows = NULL, .cols = NULL), strip.text = element_blank()) +
  theme_bw() +
  ggplotly()

在上面的代码中,我们使用 ggplotly() 函数将 ggplot 图转换为 Plotly 图,并使用 plotly() 函数在 Web 浏览器中显示。

以上是绘制多组箱形图的 ggplot 代码,希望对您有所帮助!

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的视频

领券