Plot data with different length [closed]

2019-08-27 03:12发布

问题:

I have data that looks like this:

Country Sales Year    
Germany 2000  2000
Germany 1500  2001
Germany 2150  2002
UK      1200  2000
UK      1300  2001
UK      2000  2002
Japan   500   2000
Japan   750   2001

I want to plot the data for each country and year wrt the sales value. For this purpose I use ggplot with geom_line(). The problem is that line for Japan goes down to 0 for the year 2002 since there is no data for Japan that year. What I want to do is just to stop all lines in the data at 2001 that do not represent a value, rather than seeing the dropping down to 0 in 2002.

edit: My code below. Note that I also have a vector for the size of the lines that i want to use in the real data, just remove scale_size and size to get rid of that.

ggplot(df_Filtered, aes(x = Year, y = Sales, colour = Country, scale_y_continuous(breaks = 1), size=mysize)) +  geom_line() +
    labs(x = paste("Sales per country"), y = "Sales per country", title = NULL) +
    scale_x_continuous(breaks = c(2000, 2001, 2002)) + 
    scale_size(range = c(1, 4), guide="none") +
    theme(panel.background = element_blank())
ggsave(paste("Output/", "Sales", ".png", sep = ""), width=20, height=11, limitsize = FALSE)

回答1:

Can you try this code? My graph, shown below, does not have Japan's geom_line falling to zero.

df_Filtered <- data.frame(stringsAsFactors=FALSE,
     Country = c("Germany", "Germany", "Germany", "UK", "UK", "UK", "Japan",
                 "Japan"),
       Sales = c(2000L, 1500L, 2150L, 1200L, 1300L, 2000L, 500L, 750L),
        Year = c(2000L, 2001L, 2002L, 2000L, 2001L, 2002L, 2000L, 2001L)
)

mysize <- 0.1

ggplot(df_Filtered, aes(x = Year, y = Sales, colour = Country, scale_y_continuous(breaks = 1), size=mysize)) +  geom_line() +
  labs(x = paste("Sales per country"), y = "Sales per country", title = NULL) +
  scale_x_continuous(breaks = c(2000, 2001, 2002)) + 
  scale_size(range = c(1, 4), guide="none") +
  theme(panel.background = element_blank())



标签: r ggplot2