R ggplot标签太多了

时间:2016-03-18 08:36:21

标签: r ggplot2

我有这个数据集:

<a href="http://domain.com" rel="external nofollow" target="_blank" onclick="javascript:window.open('http://domain.com');return false;ga('send','event','Outgoing Links','http://domain.com','Top content link');">Some text</a>

我使用ggplot来查看数据:

x timw                y     class
1 2010-04-01 00:00:00 843.2 normal
2 2010-04-01 00:01:00 846.3 normal
3 2010-04-01 00:02:00 838.6 normal
4 2010-04-01 00:03:00 839.9 normal
5 2010-04-01 00:04:00 841.0 normal
6 2010-04-01 00:05:00 843.3 normal
7 2010-04-01 00:06:00 844.2 normal
8 2010-04-01 00:07:00 844.6 normal
9 2010-04-01 00:08:00 840.0 normal
10 2010-04-01 00:09:00 842.2 normal

问题是打印了一个时间戳foreach点,如果我增加数据集大小,则时间戳为ovaelaps。

100 timestamps picture

我尝试在ggplot(df, aes(x=x, y=y)) + geom_point(aes(color=factor(class)))+ scale_colour_manual( values = c("normal" = "green","early warning" = "orange","changepoint" = "red"))+ theme(axis.text.x = element_text(face="bold", color="#993333", size=14, angle=90)) + scale_x_discrete(limits=as.character(df$time)) 中使用breaks参数,但它没有显示任何时间戳:

scale_x_discrete

0 timestamps picture

1 个答案:

答案 0 :(得分:1)

如果您有连续或日期时间变量,scale_x_discrete不是正确的比例。顾名思义,您只能将其用于离散(=因子或分组)变量。

因此,您必须首先确保timw变量采用正确的日期时间格式。您可以使用strptime

执行此操作
mydf$timw <- strptime(mydf$timw, format = "%Y-%m-%d %H:%M:%S", tz = "GMT")

绘图时,您可以使用scale_x_datetime设置标签的中断和格式,例如:

ggplot(mydf, aes(x = timw, y = y)) +
  geom_point() +
  scale_x_datetime(date_breaks = '1 mins', date_labels = '%H:%M') +
  theme_minimal(base_size = 14)

给出:

enter image description here

使用过的数据:

mydf <- structure(list(x = 1:10, 
                       timw = c("2010-04-01 00:00:00", "2010-04-01 00:01:00", "2010-04-01 00:02:00", "2010-04-01 00:03:00",
                                "2010-04-01 00:04:00", "2010-04-01 00:05:00", "2010-04-01 00:06:00", "2010-04-01 00:07:00", 
                                "2010-04-01 00:08:00", "2010-04-01 00:09:00"), 
                       y = c(843.2, 846.3, 838.6, 839.9, 841, 843.3, 844.2, 844.6, 840, 842.2), 
                       class = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "normal", class = "factor")), 
                  .Names = c("x", "timw", "y", "class"), row.names = c(NA, -10L), class = "data.frame")