How to remove gaps on a date axis in ggplot2

无人久伴 提交于 2020-07-22 11:56:50

问题


How do I clean these empty spaces that I have no data on?

A snippet of my dataset:

contratos.dolar <- read.table(text = "
DATA TOTAL IE II PJF PJNF PF VAR 
1 2020-02-28 1003124 178481 -168172 -11901 5497 -3905 <NA> 
2 2020-03-02 643282 140910 -127170 -28232 18187 -3695 -37571 
3 2020-03-03 665899 162927 -138690 -34084 14577 -4770 22017 
4 2020-03-04 688097 195154 -151717 -47994 9912 -5355 32227 
5 2020-03-05 739802 255604 -178552 -82204 8707 -3555 60450 
6 2020-03-06 739802 255604 -178552 -82204 8707 -3555 0", header = TRUE)

My code:

ggplot(contratos.dolar, aes(x = DATA, y = as.numeric(IE), fill = IE > 0)) +
  geom_bar(stat='identity') +
  labs(title = "Dolar futuro - Contratos em aberto", subtitle = "Investidor Estrangeiro", caption = format.Date(hoje, "%d/%m/%Y")) +
  xlab("") +
  ylab("") +
  scale_x_date(date_labels = "%d/%m", expand = c(0,0), limits = c(Sys.Date() - 40, NA), breaks = "2 day") +
  scale_y_continuous(labels = scales::comma, n.breaks = 7) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 90, hjust = 1), plot.caption = element_text(size=10, face="bold.italic")) +
  guides(fill = FALSE)

And picture of the plot I get:

My ggplt


回答1:


To get rid of the gaps in your date axis you have to convert the date column to a factor. To show only each second date I added a helper function. Try this:

contratos.dolar <- read.table(text = "
DATA TOTAL IE II PJF PJNF PF VAR 
1 2020-02-28 1003124 178481 -168172 -11901 5497 -3905 <NA> 
2 2020-03-02 643282 140910 -127170 -28232 18187 -3695 -37571 
3 2020-03-03 665899 162927 -138690 -34084 14577 -4770 22017 
4 2020-03-04 688097 195154 -151717 -47994 9912 -5355 32227 
5 2020-03-05 739802 255604 -178552 -82204 8707 -3555 60450 
6 2020-03-06 739802 255604 -178552 -82204 8707 -3555 0", header = TRUE)

contratos.dolar$DATA <- as.Date(contratos.dolar$DATA, "%Y-%m-%d")
hoje <- Sys.Date()

contratos.dolar$DATA1 <- factor(format(contratos.dolar$DATA, "%d %m"))
contratos.dolar$DATA1 <- forcats::fct_reorder(contratos.dolar$DATA1, contratos.dolar$DATA)

mybreaks <- function(x) {
  x[seq_along(x) %% 2 == 1]  
}

library(ggplot2)

ggplot(contratos.dolar, aes(x = DATA1, y = as.numeric(IE), fill = IE > 0)) +
  geom_bar(stat='identity') +
  labs(title = "Dolar futuro - Contratos em aberto", subtitle = "Investidor Estrangeiro", caption = format.Date(hoje, "%d/%m/%Y")) +
  xlab("") +
  ylab("") +
  scale_y_continuous(labels = scales::comma, n.breaks = 7) +
  scale_x_discrete(breaks = mybreaks) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 90, hjust = 1), plot.caption = element_text(size=10, face="bold.italic")) +
  guides(fill = FALSE)

Created on 2020-04-20 by the reprex package (v0.3.0)



来源:https://stackoverflow.com/questions/61331557/how-to-remove-gaps-on-a-date-axis-in-ggplot2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!