首页 > 解决方案 > 从 x 轴移除 1990 年到 2010 年之间的中间年份

问题描述

我是 R 的初学者,所以如果这是一个非常基本的问题,我提前道歉。

我正在绘制一个箱线图,显示 1990 年和 2010 年的条形类型及其各种数量。这里有两个问题:

  1. 我希望删除 1980、2000、2020 年。我尝试使用scale_x_discrete("1990","2010")但它似乎不起作用。
  2. 底部的图例列出了条的名称。但是,我希望.用空格替换。例如,更改mid.channel.barMid-channel bar.

 

library(ggplot2)
library(tidyr)
library(reshape2)

barCount <- tibble::tribble(
             ~Year, ~Lateral.bar, ~Bar.accreted.to.island, ~Mid.channel.bar,
              1990,          105,                     134,               62,
              2010,          102,                     189,              102
             )

df2 <- melt(barCount, id="Year")
barPlot <- ggplot(df2, aes(Year,value)) +
  geom_bar(aes(fill=variable),position="dodge",stat="identity") +
  labs(y="Quantity",fill="")+
  scale_fill_manual("Legend",values=c("Lateral.bar"="khaki4","Bar.accreted.to.island"="Khaki2",
                    "Mid.channel.bar"="ivory"))

#modifying axis 
barPlot <- barPlot + theme(
  axis.title.x = element_blank(),
  axis.title.y = element_text(size=14),
  axis.text.x = element_text(size=14),
  legend.position="bottom"
  )

barPlot

标签: rggplot2bar-chart

解决方案


如果您将年份列视为一个因素,ggplot 将为您提供所需的图。加上变量列上的 str_replace_all 会将点交换为空格:

library(reshape2)
library(tidyverse)
barCount <- tibble::tribble(
~Year, ~Lateral.bar, ~Bar.accreted.to.island, ~Mid.channel.bar,
1990,          105,                     134,               62,
2010,          102,                     189,              102
)


df2 <- melt(barCount, id="Year") %>% 
  mutate(
    Year = Year %>% as.factor(),
    variable = variable %>% str_replace_all("\\.", " ")
  )
barPlot <- ggplot(df2, aes(Year,value)) +
geom_bar(aes(fill=variable),position="dodge",stat="identity") +
labs(y="Quantity",fill="")+
scale_fill_manual("Legend",values=c("Lateral bar"="khaki4","Bar accreted to island"="Khaki2","Mid channel bar"="ivory"))

#modifying axis 
barPlot <- barPlot + theme(
axis.title.x = element_blank(),
axis.title.y = element_text(size=14),
axis.text.x = element_text(size=14),
legend.position="bottom"

)

barPlot

推荐阅读