科研星球

R语言绘图:Histogram及代码

我们在想要展示我们的科研成果的时候经常会需要用到一些图,其中柱状图毫无疑问是我们的常用图,做起来都比较简单。首先来看看柱状图的代码如下:


library(ggplot2)theme_set(theme_classic())
# Histogram on a Continuous (Numeric) Variableg <- ggplot(mpg, aes(displ)) + scale_fill_brewer(palette = "Spectral")
g + geom_histogram(aes(fill=class),                   binwidth = .1,                   col="black",                   size=.1) +  # change binwidth  labs(title="Histogram with Auto Binning",       subtitle="Engine Displacement across Vehicle Classes")

       结果如下所示:

下载.jpeg

修改bin的个数,代码如下:

g + geom_histogram(aes(fill=class),                    bins=5,                    col="black",                    size=.1) +   # change number of bins  labs(title="Histogram with Fixed Bins",        subtitle="Engine Displacement across Vehicle Classes")

可得如下结果:

下载 (1).jpeg

bar图代码如下:

library(ggplot2)theme_set(theme_classic())
# Histogram on a Categorical variableg <- ggplot(mpg, aes(manufacturer))g + geom_bar(aes(fill=class), width = 0.5) +  theme(axis.text.x = element_text(angle=65, vjust=0.6)) +  labs(title="Histogram on Categorical Variable",       subtitle="Manufacturer across Vehicle Classes")

       结果图如下所示:

下载 (2).jpeg


没有账号?