【发布时间】:2021-01-12 05:27:16
【问题描述】:
我想在 R / ggplot2 的条形图上重新排序 x 轴级别。我还想更改 y 轴的比例。我现在不知道该怎么做。
我从 mt_cars 数据集开始。我创建了 cyl 和 vs 变量的文本版本。
然后我创建了一个条形图,其中 x=cyl_text、y=disp、fill=vs_text。
目前,从左到右依次是“八缸”、“四缸”和“六缸”。我想将它重新排序为任何顺序,特别是以下顺序:(左)“四缸”,“六缸”,然后是“八缸”。这可以做到吗?请指教。
我还想更改 y 轴的比例。目前,刻度从 0 标记为最小刻度,从 400 标记为最大刻度。最大排量的汽车是 472,所以最高的条在刻度最大标记之上。我想将最小刻度标记更改为 -50,将最大刻度标记更改为 600。可以这样做吗?请指教。
提前谢谢。
这是条形图:
这是我用来制作条形图的代码:
# creates bar plot where x=cyl_text, y=disp, fill=vs_text, so that x level order and y scale mix and max can be changed
## dataset of interest
mtcars
### loads ggplot2 package
library(ggplot2)
### colnames of mtcars
colnames(mtcars)
### max value of mtcars$disp
max(mtcars$disp)
#### creates unique text based values of cyl
##### unique values of mtcars$cyl
unique(mtcars$cyl)
##### creates unique text based values of cyl
mtcars$cyl_text <- ifelse(mtcars$cyl == 4, "Four cylinders",
ifelse(mtcars$cyl == 6, "Six cylinders",
ifelse(mtcars$cyl == 8, "Eight cylinders", NA)
)
)
##### gives unique values for mtcars$cyl_text
unique(mtcars$cyl_text)
#### creates test version of mtcars$vs
##### unique values of mtcars$vs
unique(mtcars$vs)
##### creates unique text based values of vs
mtcars$vs_text <- ifelse(mtcars$vs == 0, "V-shaped engine",
ifelse(mtcars$vs == 1, "straight engine", NA)
)
##### gives unique values for mtcars$vs_text
unique(mtcars$vs_text)
#### creates base plot
## ---- NOTE: object name will need to be updated when changing variables
## ---- NOTE: dataset used: mtcars
bar_plot__mtcars <-
ggplot(mtcars, aes(x=cyl_text, y=disp, fill=vs_text)) +
geom_bar(stat="identity", position=position_dodge(), width = .3)
bar_plot__mtcars
#### adds labeles
## ---- NOTE: object name will need to be updated when changing variables
bar_plot__mtcars <- bar_plot__mtcars + ggtitle("Comparing number of cylinders and engine displacement\n while highlighting cars with different engine shapes") +
xlab("Number of cylinders") + ylab("engine displacement") + theme(plot.title = element_text(hjust = 0.5))
bar_plot__mtcars
bar_plot__mtcars <-
bar_plot__mtcars + theme(
panel.background = element_rect(fill = "white",
colour = "white",
size = 0.5, linetype = "solid"),
panel.grid.major = element_line(size = 0.5, linetype = 'solid',
colour = "lightblue"),
panel.grid.minor = element_line(size = 0.25, linetype = 'solid',
colour = "lightblue")
)
bar_plot__mtcars
bar_plot__mtcars <-
bar_plot__mtcars + labs(fill = "Engine shape")
bar_plot__mtcars
【问题讨论】:
-
这能回答你的问题吗? ggplot2: sorting a plot
标签: r ggplot2 plot bar-chart axis