如何在 R 中使用 ggplot2 来创建水平图例?
默认的图例方向是垂直的,但也可以改为水平的,为此,我们可以使用 ggplot2 包的 theme 函数的 legend.direction 参数。例如,如果我们要用 x 作为类别,y 作为数据帧 df 中包含的频率来创建一个条形图,那么条形图可以用 x 中的类别水平图例表示出来,创建过程如下:
ggplot(df,aes(x,y,fill=x))+geom_bar(stat="identity")+theme(legend.direction="horizontal")
示例
考虑以下数据帧 −
> x<-c("A","B","C")
> y<-c(27,25,28)
> df<-data.frame(x,y)
> df输出
x y 1 A 27 2 B 25 3 C 28
加载 ggplot2 包并创建条形图 −
示例
> library(ggplot2) > ggplot(df,aes(x,y,fill=x))+geom_bar(stat="identity")
输出

使用水平图例创建图表 −
示例
> ggplot(df,aes(x,y,fill=x))+geom_bar(stat="identity")+theme(legend.direction="horizontal")
输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP