防止ggplot2下降x轴水平

时间:2019-01-29 21:25:19

标签: r ggplot2

我正在尝试可视化一些数据,这些数据没有任何信息,因此我不希望ggplot2删除未使用的x轴位置。

我尝试了以下代码,并包含了一些虚拟数据:

public int Height()
    {
        int result = GetMaxHeight(this.Root,0);
        return result;
    }

    private int GetMaxHeight(Node<T> node,int count)
    {
        int leftMax = 0, rightMax = 0;
        if (node.Left != null)
        {
            leftMax = GetMaxHeight(node.Left, count+1);
        }
        if (node.Right != null)
        {
            rightMax = GetMaxHeight(node.Right, count + 1);
        }

        if(node.Left==null && node.Right == null)
        {
            return count;
        }

        return Math.Max(leftMax,rightMax);
    }

给出了一个图,其中在x轴上放置了租约'1',但是我希望能够包括租约'1',因为它没有记录数据很重要。

enter image description here

2 个答案:

答案 0 :(得分:2)

对应级别1的变量值始终为NA。这就是ggplot删除x值的原因。值为零时,ggplot不会删除x的值

lease   <-c(1,  2,  3,  1,  2,  3,  1,  2,  3)
year<-c(2017,   2017,   2017,   2018,   2018,   2018,   2018,   2018,   2018)
variable<-c(0, 1,  1,  0, 1,  1,  0, 1,  1)
location<-  c('in', 'in',   'in',   'in',   'in',   'in',   'out',  'out',  'out')

dft<-data.frame(lease, year, variable, location)
dft%>%
  mutate_all(as.character)%>%
  filter(!is.na(variable))%>%
  ggplot(aes(x=factor(lease), fill = variable)) +
  geom_bar(stat = 'Count', position = 'stack') + facet_grid(location~year) + 
  guides(fill=guide_legend(title="Level"))

enter image description here

答案 1 :(得分:1)

另一个选项提供了drop中的facet_grid自变量。

dft %>%
  mutate_all(as.character) %>%
  # filter(!is.na(variable)) %>%
  ggplot(aes(x = lease, fill = variable)) +
  geom_bar(stat = 'Count', position = 'stack') + 
  facet_grid(location ~ year, drop = FALSE) +
  guides(fill = guide_legend(title = "Level")) +
  scale_x_discrete(labels = c("", 2, 3)) +      # change labels
  theme(axis.ticks.x = element_blank())         # remove axis ticks

enter image description here


如果我们要显示存在NA的空白处,我们可以将lease转换为一个因数并执行

dft %>%
  mutate(lease = factor(lease)) %>%
  filter(!is.na(variable)) %>%
  ggplot(aes(x = lease, fill = variable)) +
  geom_bar(stat = 'count') + 
  facet_grid(location ~ year) +
  guides(fill = guide_legend(title = "Level")) +
  scale_x_discrete(drop = FALSE)

enter image description here