画出左侧对齐的柱状图并且添加标签的R语言代码
时间: 2023-11-28 12:51:35 浏览: 59
假设我们有以下数据:
```
data <- data.frame(category = c("A", "B", "C", "D", "E"),
value = c(10, 20, 15, 5, 12))
```
则可以使用以下 R 代码绘制左对齐的柱状图并添加标签:
```
library(ggplot2)
ggplot(data, aes(x = category, y = value)) +
geom_bar(stat = "identity", width = 0.5, fill = "blue") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 90, hjust = 0),
axis.title.x = element_blank()) +
labs(y = "Value",
title = "Left-aligned Bar Chart",
subtitle = "Using ggplot2") +
geom_text(aes(label = value), hjust = -0.2, size = 4, color = "white")
```
解释一下代码:
- `aes(x = category, y = value)`:设置 X 轴为 category 列,Y 轴为 value 列;
- `geom_bar(stat = "identity", width = 0.5, fill = "blue")`:绘制柱状图,`stat = "identity"` 表示使用原始数据作为柱状图高度,`width = 0.5` 表示柱宽为 0.5,`fill = "blue"` 表示柱状图填充颜色为蓝色;
- `theme_minimal()`:设置主题为 minimal;
- `theme(axis.text.x = element_text(angle = 90, hjust = 0), axis.title.x = element_blank())`:设置 X 轴文字方向为 90 度,左对齐,去掉 X 轴标题;
- `labs(y = "Value", title = "Left-aligned Bar Chart", subtitle = "Using ggplot2")`:设置 Y 轴标题为 Value,标题为 Left-aligned Bar Chart,副标题为 Using ggplot2;
- `geom_text(aes(label = value), hjust = -0.2, size = 4, color = "white")`:在柱状图上添加标签,`aes(label = value)` 表示标签显示 value 列,`hjust = -0.2` 表示标签左对齐,`size = 4` 表示标签大小为 4,`color = "white"` 表示标签颜色为白色。
阅读全文