1

我试图让这个图由多条彩色线组成,一条代表每年,只显示沿 X 轴的月份。一旦我format()用作 X in 的值aes,我就只能使用scale_x_discrete. 从那里,我无法弄清楚如何只显示月份,并且只显示一次。

绘图是正确的,但中断和标签不正确。最重要的是,休息。因为一年中的日子通常不会重叠,所以我也得到了太多的中断值。您可以看到两条注释掉的行并排在一起,这是我试图解决问题的地方。

我真正想要的是在 X 轴上形成中断,并按月份标记。


数据集:Retail_Gas_Prices.csv

require(ggplot2)  # ggplot
require(reshape)  # melt
require(scales)   # date_format

# monthtext <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
gp <- read.csv("Retail_Gas_Prices.csv")
gp$Month <- substr(gp$Date, 1, 2)
gp$Year <- substr(gp$Date, 7, 10)
gp$Date <- as.Date(substr(gp$Date, 1, 10), "%m/%d/%Y")

coord_radar <- function(...) {
  structure(coord_polar(...), class = c("radar", "polar", "coord"))
}

gas_ra_plot <- ggplot(gp, aes(x=format(Date, '%m:%w:%d'), y=Weekly.US, group=Year, color=Year)) +
  geom_line()+
#   coord_polar()+
  labs(title = "Gas Prices by Month")+
  scale_x_discrete(expand = c(0.0, 0.0))+
#   scale_x_discrete(breaks = seq(1,12,1), expand = c(0.0, 0.0))+
#   scale_x_discrete(breaks = seq(min(gp$Date),max(gp$Date), length(gp$Date)/12), expand = c(0.0, 0.0))+
  scale_y_continuous(expand = c(0.0, 0.0))+
  ylab("Cost in Dollars") +
  theme(axis.ticks = element_blank())+
  theme(axis.title.x = element_blank())+

  theme(strip.background = element_blank())+
  theme(panel.background = element_blank())+
  theme(panel.grid.major.x = element_line(
    colour = "#dddddd"))


print(gas_ra_plot)
4

1 回答 1

2
gp <- read.csv('http://share.kevin-funk.com/Retail_Gas_Prices.csv')

require(ggplot2) 
require(scales)

#parse the datetimes
gp$Date <- strptime(as.character(gp$Date),"%m/%d/%Y %I:%M:%S %p %z",tz="GMT")

#create year variable
gp$Year <- format(gp$Date,"%Y")

#create dates with the same year (2013)
gp$Date1 <- as.Date(format(gp$Date,"%m-%d"),"%m-%d")

#might be better to make this 2012 due to Feb-29
gp$Date1 <- as.Date(paste0("2012-",format(gp$Date,"%m-%d")),"%Y-%m-%d")


gas_ra_plot <- ggplot(gp, aes(x=Date1, y=Weekly.US, group=Year, color=Year)) +
  geom_line()+
  scale_x_date(labels = date_format("%b-%d"))

print(gas_ra_plot)
于 2013-03-17T10:58:56.227 回答