简体   繁体   中英

R Histogram Change X-Axis Incremental Value

I am trying to make my histogram's x-axis go from 2000 to 2016 counting by 1. Right now, as shown in the picture, it is counting by 5. I tried using the following statement to no avail:

axis(side=1, at=seq(1999,2017, 1)))

Any help addressing this issue would be much appreciated

df <- read.table(textConnection(
  'Year Count
  2016  1
  2015  7
  2014  8
  2013  3
  2012  13
  2011  3
  2010  6
  2009  2
  2008  2
  2007  3
  2006  1
  2005  0
  2004  1
  2003  7
  2002  1
  2001  3
  2000  0'), header = TRUE)

hw <- theme_gray()+ theme(
  plot.title=element_text(hjust=0.5,face='bold',size=16),
  axis.title.y=element_text(angle=0,vjust=.5,face='bold',size=13),
  axis.title.x=element_text(face='bold',size=13),
  plot.subtitle=element_text(hjust=0.5),
  plot.caption=element_text(hjust=-.5),

  strip.text.y = element_blank(),
  strip.background=element_rect(fill=rgb(.9,.95,1),
                                colour=gray(.5), size=.2),

  panel.border=element_rect(fill=FALSE,colour=gray(.70)),
  panel.grid.minor.y = element_blank(),
  panel.grid.minor.x = element_blank(),
  panel.spacing.x = unit(0.10,"cm"),
  panel.spacing.y = unit(0.05,"cm"),

  axis.ticks=element_blank(),
  axis.text=element_text(colour="black"),
  axis.text.y=element_text(margin=margin(0,3,0,3),face="bold",size=10),
  axis.text.x=element_text(margin=margin(-1,0,3,0),face="bold",size=10)
)




dfnew=NULL
for (row in 1:nrow(df))
{
  temp=rep(df[row,]$Year,df[row,]$Count)
  dfnew = rbind(dfnew,data.frame(Year=temp))
}
df=dfnew


library(ggplot2)


ggplot(df,aes(x=Year)) +
  geom_histogram()+
  labs(x="Year",
       y="Count",
       title="Year vs MLB No-Hitters Count")+hw


ggplot(df,aes(x=Year)) +
  geom_histogram(binwidth=1,
                 fill="cornsilk",color="black")+
  labs(x="Year",
       y="Count",
       title="Year vs MLB No-Hitters Count")+hw


ggplot(df,aes(x=Year,..density..)) +
  geom_histogram(binwidth=1,
                 fill="cornsilk",color="black")+
  labs(x="Year",
       y="Count",
       title="Year vs MLB No-Hitters Count")+hw




histPlot <- ggplot(df,aes(x=Year,..density..))+
  geom_histogram(binwidth=1, fill="cornsilk",color="black")+
  labs(x="Year",
       y="Density",
       title="Year vs MLB No-Hitters Count")+hw


histPlot


histPlot + geom_freqpoly(binwidth=1,color="red",size=1.2)


histPlot + geom_line(stat="density",color="blue",size=1.2)+
  xlim(1999,2017)


histPlot +
  geom_density(adjust=.4,fill="cyan",color="black",alpha=.40)+
  xlim(1999,2017)

在此处输入图片说明

Another ggplot option. You'll need to rotate the text 90 degrees though.

+ scale_x_continuous(breaks=c(2000:2016))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM