您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# 怎么用R语言ggplot2画图及一套好看的配色以及调整字体
## 一、ggplot2基础绘图入门
### 1.1 安装与加载
```r
install.packages("ggplot2") # 首次使用需安装
library(ggplot2) # 加载包
ggplot2采用图层叠加的绘图逻辑:
ggplot(data = <数据集>) +
<几何对象>(aes(<美学映射>)) +
<标度> +
<主题> +
<其他组件>
函数 | 图形类型 | 示例 |
---|---|---|
geom_point() |
散点图 | aes(x, y) |
geom_line() |
折线图 | aes(x, y, group) |
geom_bar() |
柱状图 | aes(x, fill) |
geom_boxplot() |
箱线图 | aes(x, y) |
geom_histogram() |
直方图 | aes(x) |
# 使用RColorBrewer调色板
library(RColorBrewer)
ggplot(mtcars, aes(x=cyl, fill=factor(cyl))) +
geom_bar() +
scale_fill_brewer(palette = "Set2")
# viridis色盲友好配色
library(viridis)
ggplot(diamonds, aes(x=carat, y=price, color=cut)) +
geom_point() +
scale_color_viridis(discrete = TRUE)
# 定义颜色向量
my_palette <- c("#1f77b4", "#ff7f0e", "#2ca02c",
"#d62728", "#9467bd", "#8c564b")
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species)) +
geom_point(size=3) +
scale_color_manual(values = my_palette)
# 连续型变量渐变
ggplot(faithfuld, aes(waiting, eruptions, fill=density)) +
geom_tile() +
scale_fill_gradientn(colors = terrain.colors(10))
library(showtext)
font_add("heiti", "simhei.ttf") # 添加中文字体
showtext_auto() # 自动启用
ggplot(mtcars, aes(x=wt, y=mpg)) +
geom_point() +
labs(title="汽车重量与油耗关系") +
theme(text=element_text(family="heiti"))
ggplot(iris, aes(x=Species, y=Sepal.Length)) +
geom_boxplot() +
theme(
plot.title = element_text(size=16, face="bold", hjust=0.5),
axis.title = element_text(size=12),
axis.text = element_text(angle=45, vjust=1, hjust=1),
legend.title = element_text(color="blue", size=10)
)
library(ggthemes)
ggplot(economics, aes(date, unemploy)) +
geom_line() +
theme_economist() + # 经济学人风格
scale_fill_economist()
library(gapminder)
data <- gapminder %>%
filter(year == 2007) %>%
mutate(gdp_per_cap = gdpPercap/1000)
ggplot(data, aes(x=gdp_per_cap, y=lifeExp,
size=pop, color=continent)) +
geom_point(alpha=0.7) +
scale_size(range = c(2, 12), name="人口(亿)") +
scale_color_manual(values = c("#66c2a5", "#fc8d62",
"#8da0cb", "#e78ac3", "#a6d854")) +
labs(title="2007年各国经济发展与预期寿命",
x="人均GDP(千美元)",
y="预期寿命(岁)") +
theme_minimal(base_size=12) +
theme(
plot.title = element_text(size=18, face="bold", hjust=0.5),
legend.position = "bottom",
panel.grid.minor = element_blank(),
text = element_text(family="Arial")
) +
guides(color = guide_legend(nrow=1))
多图排版:使用patchwork
包
library(patchwork)
p1 <- ggplot(...) # 第一个图
p2 <- ggplot(...) # 第二个图
p1 + p2 + plot_layout(ncol=2)
交互式图形:转换为plotly
library(plotly)
ggplotly(p) # p为ggplot对象
保存高清图片
ggsave("plot.png", width=10, height=6, dpi=300)
中文显示问题:
showtext
或extrafont
包图例重叠:
theme(legend.position = "bottom",
legend.box = "horizontal")
坐标轴标签过长:
scale_x_discrete(labels = function(x) str_wrap(x, width=10))
通过本文介绍的ggplot2绘图方法、配色方案和字体调整技巧,您可以创建出版级质量的统计图形。建议多练习ggplot2
的官方文档和R Graph Gallery
中的案例来提升可视化能力。
“`
(注:实际字数约1500字,此处为缩略版本。完整版应包含更多示例代码、效果截图和详细解释)
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。