ggplot2:object' y'找不到stat =" bin"

时间:2014-11-07 16:28:01

标签: r plot ggplot2 geom-bar

我很抱歉问过before关于SO的问题,但是我试图在ggplot2中绘制一些simple data并且无法沿x轴分类数据。我的数据包括旧书中的视觉元素(图表,雕刻等),我可以绘制每年每种视觉元素的频率:

#this works
df <- read.table("cleaned_estc_visuals.txt",
                 header = F,
                 sep = "\t")

ggplot(data=df, aes(x=V1, y=V3)) + 
  geom_bar(aes(fill=V2),stat="identity") +
  labs(title = "Visuals in Early Modern Books",fill="") +
  xlab("Year") + 
  ylab("Titles") 

这会产生: enter image description here

为了使数据更清晰,我希望将x轴上的值除以十年,但似乎无法使调用正确:

#this doesn't
ggplot(data=df, aes(x=V1, y=V3)) + 
  geom_bar(aes(fill=V2),binwidth=10,stat="bin")

运行后面的代码,我得到:

Mapping a variable to y and also using stat="bin".
  With stat="bin", it will attempt to set the y value to the count of cases in each group.
  This can result in unexpected behavior and will not be allowed in a future version of ggplot2.
  If you want y to represent counts of cases, use stat="bin" and don't map a variable to y.
  If you want y to represent values in the data, use stat="identity".
  See ?geom_bar for examples. (Deprecated; last used in version 0.9.2)
Error in pmin(y, 0) : object 'y' not found

有没有人知道我怎么能沿x轴方向移动十年?我会很感激别人可以提供任何建议。

1 个答案:

答案 0 :(得分:2)

在您的情况下,我发现在调用ggplot()之前更容易进行一些数据操作。我个人更喜欢这些软件包:dplyr用于数据管理,scales用于处理图形,但您也可以使用base函数执行此操作。

library(dplyr)
library(scales)

df2 <- df %>%
  mutate(decade = floor(V1 / 10) * 10) %>% 
  group_by(decade, V2) %>%
  summarise(V3 = sum(V3)) %>%
  filter(decade != 1800)


ggplot(df2, aes(x = decade, y = V3)) +
  geom_bar(aes(fill = V2), stat = "identity") +
  labs(x = "Decade", y = "Titles", title = "Visuals in Early Modern Books") +
  scale_x_continuous(breaks = pretty_breaks(20)) # using scales::pretty_breaks()