在`geom_bar`中将轴刻度标签更改为月份名称和表达式

kh212irz  于 2023-04-09  发布在  其他
关注(0)|答案(2)|浏览(129)

我正在尝试为这些数据定制一个图。

x <- 1:12
z1 <- c("m", "m", "m", "m", "m", "n", "n", "n", "n", "n", "n", "n")
z2 <- c("m", "m", "m", "m", "p", "p", "p", "p", "n", "n", "n", "n")
z3 <- c("m", "m", "m", "p", "p", "p", "n", "n", "n", "n", "n", "n")

所以我创建了一个数据框并绘制了它。

df <- data.frame(x, z1, z2, z3)
colors <- c("m" = "#f8766d", "n" = "#00BA38", "p" = "#619CFF")

df_long <- pivot_longer(df, cols = c("z1", "z2", "z3"), names_to = "variable", values_to = "value")

df_long$value <- factor(df_long$value, levels = c("m", "n", "p"))

ggplot(df_long, aes(x = variable, fill = value)) +
  geom_bar(position = position_stack(reverse = TRUE)) +
  coord_flip()

输出还不错;看起来是这样的。

但是我们希望在x轴上有三个刻度,分别是JanFebMar。所以Janx=1的位置,然后Febx=5的位置,Marx=9的位置。
在y轴上,我们希望有z(t,1)z(t,2)z(t,3),但以斜体显示,就像我们在标签中对expression()所做的那样。
有可能做到吗?有人能帮帮忙吗?

fhg3lkii

fhg3lkii1#

从绘图对象p开始,您可以更改和自定义刻度线和标签。
正如你提到的,Jan被放置在x=1的位置(m、n或p出现1次,Feb出现5次)

p=ggplot(df_long, aes(x = variable, fill = value)) +
  geom_bar(position = position_stack(reverse = TRUE)) +
  coord_flip()
p +  theme(axis.text.y = element_text(face="italic")) +
    scale_x_discrete(breaks=c("z1","z2","z3"),
                      labels=c("z(t,1)", "z(t,2)", "z(t,3)"))+
    scale_y_continuous(breaks=c(1,5,9),
                     labels=c("Jan", "Feb", "Mar"))

创建于2023-04-03带有reprex v2.0.2

plupiseo

plupiseo2#

library(ggplot2)
library(tidyr)

x <- 1:12
z1 <- c("m", "m", "m", "m", "m", "n", "n", "n", "n", "n", "n", "n")
z2 <- c("m", "m", "m", "m", "p", "p", "p", "p", "n", "n", "n", "n")
z3 <- c("m", "m", "m", "p", "p", "p", "n", "n", "n", "n", "n", "n")

df <- data.frame(x = factor(x), z1, z2, z3) # convert x to a factor

colors <- c("m" = "#f8766d", "n" = "#00BA38", "p" = "#619CFF")

df_long <- pivot_longer(df, cols = c("z1", "z2", "z3"), names_to = "variable", values_to = "value")

df_long$value <- factor(df_long$value, levels = c("m", "n", "p"))

ggplot(df_long, aes(x = variable, fill = value)) +
  geom_bar(position = position_stack(reverse = TRUE)) +
  scale_x_discrete(labels = expression("Jan", "Feb", "Mar")) +
  ylab(expression(italic("z"(t,1:3)))) +
  theme(axis.text.y = element_text(face = "italic"))

你是说像这样的东西吗

相关问题