在R和y轴上以不同比例添加文本到水平条形图可以使用R中的ggplot2包来实现。
首先,需要加载ggplot2包,可以使用以下命令:
library(ggplot2)
然后,可以使用以下代码来创建水平条形图:
ggplot(data = df, aes(x = loc, y = cars_sold)) +
geom_col(fill = "darkblue") +
coord_flip() +
labs(title = "Number of Cars Sold by Dealership") +
facet_wrap(~V1) +
theme_bw() +
theme(panel.border = element_blank(), panel.grid = element_blank(), strip.text = element_blank())
其中,df
是数据集,loc
是地点,cars_sold
是汽车销量,V1
是分组变量。
接下来,可以使用以下代码来在R和y轴上添加文本:
ggplot(data = df, aes(x = loc, y = cars_sold)) +
geom_col(fill = "darkblue") +
coord_flip() +
labs(title = "Number of Cars Sold by Dealership") +
facet_wrap(~V1) +
theme_bw() +
theme(panel.border = element_blank(), panel.grid = element_blank(), strip.text = element_blank()) +
geom_text(aes(label = cars_sold), hjust = -0.2, color = "white", size = 3) +
geom_line(aes(y = cars_sold, group = 1, color = "Cars Sold"), size = 1) +
geom_point(aes(y = cars_sold, group = 1, color = "Cars Sold"), size = 2)
其中,geom_text
函数用于在R轴上添加文本,geom_line
和geom_point
函数用于在y轴上添加线条和点,颜色由color = "Cars Sold"
指定。
最终,可以使用以下代码来生成图形:
ggplot(data = df, aes(x = loc, y = cars_sold)) +
geom_col(fill = "darkblue") +
coord_flip() +
labs(title = "Number of Cars Sold by Dealership") +
facet_wrap(~V1) +
theme_bw() +
theme(panel.border = element_blank(), panel.grid = element_blank(), strip.text = element_blank()) +
geom_text(aes(label = cars_sold), hjust = -0.2, color = "white", size = 3) +
geom_line(aes(y = cars_sold, group = 1, color = "Cars Sold"), size = 1) +
geom_point(aes(y = cars_sold, group = 1, color = "Cars Sold"), size = 2)
这将生成以下图形:
领取专属 10元无门槛券
手把手带您无忧上云