将准备用直方图展示的数据整理在excel中,每个变量一列,比如本文用到的例子

image.png 将其另存为csv格式。 以上数据来源 https://www.r-graph-gallery.com/220-basic-ggplot2-histogram.html
exampledfpath<-file.choose() ###运行这一行命令,跳出对话框,选择刚刚保存的csv格式的数据
df<-read.csv(exampledfpath,header=TRUE) ### 运行这一行命令读入数据
header=TRUE参数是因为刚刚保存的数据中有表头,如果自己的数据没有表头,可以将参数设置为header=FALSE,这样表头就自动设置为了V1
library(ggplot2) ###加载ggplot2作图包
如果遇到报错Error in library(ggplot2) : 不存在叫‘ggplot2’这个名字的程辑包
说明没有安装ggplot2这个包,运行命令安装,再加载
install.packages("ggplot2")
library(ggplot2)ggplot(data=df,aes(x=price)) +
geom_histogram(binwidth=15,fill="#69b3a2",
color="#e9ecef", alpha=0.9)+
theme_bw()+
labs(x="",y="")
image.png
df是你读入的数据
price是你数据中的变量名
binwidth设置的是柱子的宽窄,根据需要调大或者调小
以下是binwidth设置不同的参数的区别
p1<-ggplot(data=df,aes(x=price)) +
geom_histogram(binwidth=30,fill="#69b3a2",
color="#e9ecef", alpha=0.9)+
theme_bw()+
labs(x="",y="",title="binwidth=30")
p2<-ggplot(data=df,aes(x=price)) +
geom_histogram(binwidth=10,fill="#69b3a2",
color="#e9ecef", alpha=0.9)+
theme_bw()+
labs(x="",y="",title="binwidth=30")
ggpubr::ggarrange(p1,p2,ncol=1,nrow=2)

image.png
fill设置的是柱子内部的填充颜色
color设置的是柱子边框的颜色
alpha设置的是柱子填充颜色的透明度,范围是0~1.
分别设置不同的参数感受一下区别
p1<-ggplot(data=df,aes(x=price)) +
geom_histogram(binwidth=10,fill="blue",
color="red", alpha=0.5)+
theme_bw()
p2<-ggplot(data=df,aes(x=price)) +
geom_histogram(binwidth=10,fill="darkgreen",
color="orange", alpha=0.8)+
theme_bw()
ggpubr::ggarrange(p1,p2,ncol=1,nrow=2)

image.png
theme_bw()函数是去掉图片整体的灰色背景
感受一下加theme_bw()函数和不添加theme_bw()函数的区别
p1<-ggplot(data=df,aes(x=price)) +
geom_histogram(binwidth=10,fill="blue",
color="red", alpha=0.5)+
theme_bw()+labs(x="",y="",title="theme_bw()")
p2<-ggplot(data=df,aes(x=price)) +
geom_histogram(binwidth=10,fill="darkgreen",
color="orange", alpha=0.8)+
labs(x="",y="",title="no theme_bw()")
ggpubr::ggarrange(p1,p2,ncol=1,nrow=2)
image.png
labs()函数里的x和y参数分别设置的是x坐标轴和y坐标轴的标签
感受一下设置为不同值的区别
p1<-ggplot(data=df,aes(x=price)) +
geom_histogram(binwidth=10,fill="blue",
color="red", alpha=0.5)+
theme_bw()+labs(x="你好呀!",y="你吃饭了吗?",title="theme_bw()")
p2<-ggplot(data=df,aes(x=price)) +
geom_histogram(binwidth=10,fill="darkgreen",
color="orange", alpha=0.8)+
labs(x="还得细心做实验呀!",y="要认真看论文呀!",title="no theme_bw()")
ggpubr::ggarrange(p1,p2,ncol=1,nrow=2)

image.png
title参数是用来个图的左上角添加标题的
p1<-ggplot(data=df,aes(x=price)) +
geom_histogram(binwidth=10,fill="blue",
color="red", alpha=0.5)+
theme_bw()+labs(x="你好呀!",y="你吃饭了吗?",
title="title参数用到的不太多")
p1
