I am interested in plotting the results from the following code which produces a frequency distribution table. I would like to graph the Freq column as a bar with the cum.Freq as a line both sharing the interval column as the x-axis.
library("qdap")
x <- c(1,2,3,2,4,2,5,4,6,7,8,9)
dist_tab(x)
I have been able to get the bar chart built using ggplot, but I want to take it further with the cum.Freq added as a secondary axis. I also want to add the percent and cum.percent values added as data labels. Any help is appreciated.
library("ggplot2")
ggplot(dist_tab(x), aes(x=interval)) + geom_bar(aes(y=Freq))
Not sure if I understand your question. Is this what you are looking for?
df <- dist_tab(x)
df.melt <- melt(df, id.vars="interval", measure.vars=c("Freq", "cum.Freq"))
#
ggplot(df.melt, aes(x=interval, y=value, fill=variable)) +
geom_bar(stat="identity", position="dodge")
Related
I love ggplot, but find it hard to customize some elements such as X axis labels and grid lines. The title of the question says it all, but here's a reproducible example to go with it:
Reproducible example
library(ggplot2)
library(dplyr)
# Make a dataset
set.seed(123)
x1 <- c('2015_46','2015_47','2015_48','2015_49'
,'2015_50','2015_51','2015_52','2016_01',
'2016_02','2016_03')
y1 <- runif(10,0.0,1.0)
y2 <- runif(10,0.5,2.0)
# Make the dataset ggplot friendly
df_wide <- data.table(x1, y1, y2)
df_long <- melt(df_wide, id = 'x1')
# Plot it
p <- ggplot(df_long, aes(x=x1,
y=value,
group=variable,
colour=variable )) + geom_line(size=1)
plot(p)
# Now, plot the same thing with the same lines and numbers,
# but with increased space between x-axis labels
# and / or space between x-axis grid lines.
Plot1
The plot looks like this, and doesn't look too bad in it's current form:
Plot2
The problem occurs when the dataset gets bigger, and the labels on the x-axis start overlapping each other like this:
What I've tried so far:
I've made several attempts using scale_x_discrete as suggested here, but I've had no luck so far. What really bugs me is that I saw some tutorial about these things a while back, but despite two days of intense googling I just can't find it. I'm going to update this section when I try new things.
I'm looking forward to your suggestions!
As mentioned above, assuming that x1 represents a year_day, ggplot provides sensible defaults for date scales.
First make x1 into a valid date format, then plot as you already did:
df_long$x1 <- strptime(as.character(df_long$x1), format="%Y_%j")
ggplot(df_long, aes(x=x1, y=value, group=variable, colour=variable)) +
geom_line(size=1)
The plot looks a little odd because of the disconnected time series, but scales_x_date() provides an easy way to customize the axis:
http://docs.ggplot2.org/current/scale_date.html
I have a little problem with a ggplot barchart.
I wanted to make a barchart with ggplot2 in order to compare my Svolumes for my 4 stocks on a period of few months.
I have two problems:
The first one is that my y axis is wrong. My graph/data seems correct but the y axis don't "follow" as I thought it will contain another scale... I would to have to "total" number of my dataset svolumes, I think here it is writing my svolumes values. I don't know how to explain but I would like the scale corresponding to all of my data on the graph like 10,20,etc until my highest sum of svolumes.
There is my code:
Date=c(rep(data$date))
Subject=c(rep(data$subject))
Svolume=c(data$svolume)
Data=data.frame(Date,Subject,Svolume)
Data=ddply(Data, .(Date),transform,pos=cumsum(as.numeric(Svolume))-(0.5*(as.numeric(Svolume))))
ggplot(Data, aes(x=Date, y=Svolume))+
geom_bar(aes(fill=Subject),stat="identity")+
geom_text(aes(label=Svolume,y=pos),size=3)
and there is my plot:
I helped with the question here
Finally, How could I make the same plot for each months please? I don't know how to get the values per month in order to have a more readable barchart as we can't read anything here...
If you have other ideas for me I would be very glad to take any ideas and advices! Maybe the same with a line chart would be more readable...? Or maybe the same barchart for each stocks ? (I don't know how to get the values per stock either...)
I just found how to do it with lines.... but once again my y axis is wrong, and it's not very readable....
Thanks for your help !! :)
Try adding the following line right before your ggplot function. It looks like your y-axis is in character.
[edit] Incorporate #user20650's comments, add as.character() first then convert to numeric.
Data$Svolume <- as.numeric(as.character(Data$Svolume))
To produce the same plot for each month, you can add the month variable first: Data$Month <- month(as.Date(Date)). Then add facet to your ggplot object.
ggplot(Data, aes(x=Date, y=Svolume) +
...
+ facet_wrap(~ Month)
For example, your bar chart code will be:
Data$Svolume <- as.numeric(as.character(Data$Svolume))
Data$Month <- month(as.Date(Date))
ggplot(Data, aes(x=Date, y=Svolume)) +
geom_bar(aes(fill=Subject),stat="identity") +
geom_text(aes(label=Svolume,y=pos),size=3) +
facet_wrap(~ Month)
and your Line chart code will be:
Data$Svolume <- as.numeric(as.character(Data$Svolume))
Data$Month <- month(as.Date(Date))
ggplot(Data, aes(x=Date, y=Svolume, colour=Subject)) +
geom_line() +
facet_wrap(~ Month)
I have successfully created a very nice boxplot (for my purposes) categorized by a factor and binned, according to the answer in my previous post here:
ggplot: arranging boxplots of multiple y-variables for each group of a continuous x
Now, I would like to customize the x-axis labels according to the number of observations in each boxplot.
require (ggplot2)
require (plyr)
library(reshape2)
set.seed(1234)
x<- rnorm(100)
y.1<-rnorm(100)
y.2<-rnorm(100)
y.3<-rnorm(100)
y.4<-rnorm(100)
df<- (as.data.frame(cbind(x,y.1,y.2,y.3,y.4)))
dfmelt<-melt(df, measure.vars = 2:5)
dfmelt$bin <- factor(round_any(dfmelt$x,0.5))
dfmelt.sum<-summary(dfmelt$bin)
ggplot(dfmelt, aes(x=bin, y=value, fill=variable))+
geom_boxplot()+
facet_grid(.~bin, scales="free")+
labs(x="number of observations")+
scale_x_discrete(labels= dfmelt.sum)
dfmelt.sum only gives me the total number of observations for each bin not for each boxplot.
Boxplots statistics give me the number of observations for each boxplot.
dfmelt.stat<-boxplot(value~variable+bin, data=dfmelt)
dfmelt.n<-dfmelt.stat$n
But how do I add tick marks and labels for each boxplot?
Thanks, Sina
UPDATE
I have continued working on this. The biggest problem is that in the code above, only one tick mark is provided per facet. Since I also wanted to plot the means for each boxplot, I have used interaction to plot each boxplot individually, which also adds tick marks on the x-axis for each boxplot:
require (ggplot2)
require (plyr)
library(reshape2)
set.seed(1234) x<- rnorm(100)
y.1<-rnorm(100)
y.2<-rnorm(100)
y.3<-rnorm(100)
y.4<-rnorm(100)
df<- (as.data.frame(cbind(x,y.1,y.2,y.3,y.4))) dfmelt<-melt(df, measure.vars = 2:5)
dfmelt$bin <- factor(round_any(dfmelt$x,0.5))
dfmelt$f2f1<-interaction(dfmelt$variable,dfmelt$bin)
dfmelt_mean<-aggregate(value~variable*bin, data=dfmelt, FUN=mean)
dfmelt_mean$f2f1<-interaction(dfmelt_mean$variable, dfmelt_mean$bin)
dfmelt_length<-aggregate(value~variable*bin, data=dfmelt, FUN=length)
dfmelt_length$f2f1<-interaction(dfmelt_length$variable, dfmelt_length$bin)
On the side: maybe there is a more elegant way to combine all those interactions. I'd be happy to improve.
ggplot(aes(y = value, x = f2f1, fill=variable), data = dfmelt)+
geom_boxplot()+
geom_point(aes(x=f2f1, y=value),data=dfmelt_mean, color="red", shape=3)+
facet_grid(.~bin, scales="free")+
labs(x="number of observations")+
scale_x_discrete(labels=dfmelt_length$value)
This gives me tick marks on for each boxplot which can be potentially labeled. However, using labels in scale_x_discrete only repeats the first four values of dfmelt_length$value in each facet.
How can that be circumvented?
Thanks, Sina
look at this answer, It is not on the label but it works - I have used this
Modify x-axis labels in each facet
You can also do as follows, I also have used that
library(ggplot2)
df <- data.frame(group=sample(c("a","b","c"),100,replace=T),x=rnorm(100),y=rnorm(100)*rnorm(100))
xlabs <- paste(levels(df$group),"\n(N=",table(df$group),")",sep="")
ggplot(df,aes(x=group,y=x,color=group))+geom_boxplot()+scale_x_discrete(labels=xlabs)
This also works
library(ggplot2)
library(reshape2)
df <- data.frame(group=sample(c("a","b","c"),100,replace=T),x=rnorm(100),y=rnorm(100)*rnorm(100))
df1 <- melt(df)
df2 <- ddply(df1,.(group,variable),transform,N=length(group))
df2$label <- paste0(df2$group,"\n","(n=",df2$N,")")
ggplot(df2,aes(x=label,y=value,color=group))+geom_boxplot()+facet_grid(.~variable)
I have created a graph in ggplot2 using zoo to create month bins. However, I want to be able to modify the graph so it looks like a standard ggplot graph. This means that the bins that aren't used are dropped and the bins that are populate the entire bin space. Here is my code:
library(data.table)
library(ggplot2)
library(scales)
library(zoo)
testset <- data.table(Date=as.Date(c("2013-07-02","2013-08-03","2013-09-04","2013-10-05","2013-11-06","2013-07-03","2013-08-04","2013-09-05","2013-10-06","2013-11-07")),
Action = c("A","B","C","D","E","B","A","B","C","A","B","E","E","C","A"),
rating = runif(30))
The ggplot call is:
ggplot(testset, aes(as.yearmon(Date), fill=Action)) +
geom_bar(position = "dodge") +
scale_x_yearmon()
I'm not sure what I'm missing, but I'd like to find out! Thanks in advance!
To get a "standard-looking" plot, convert the data to a "standard" data type, which is a factor:
ggplot(testset, aes(as.factor(as.yearmon(Date)), fill=Action)) +
geom_bar(position='dodge')
What I really want to do is plot a histogram, with the y-axis on a log-scale. Obviously this i a problem with the ggplot2 geom_histogram, since the bottom os the bar is at zero, and the log of that gives you trouble.
My workaround is to use the freqpoly geom, and that more-or less does the job. The following code works just fine:
ggplot(zcoorddist) +
geom_freqpoly(aes(x=zcoord,y=..density..),binwidth = 0.001) +
scale_y_continuous(trans = 'log10')
The issue is that at the edges of my data, I get a couple of garish vertical lines that really thro you off visually when combining a bunch of these freqpoly curves in one plot. What I'd like to be able to do is use points at every vertex of the freqpoly curve, and no lines connecting them. Is there a way to to this easily?
The easiest way to get the desired plot is to just recast your data. Then you can use geom_point. Since you don't provide an example, I used the standard example for geom_histogram to show this:
# load packages
require(ggplot2)
require(reshape)
# get data
data(movies)
movies <- movies[, c("title", "rating")]
# here's the equivalent of your plot
ggplot(movies) + geom_freqpoly(aes(x=rating, y=..density..), binwidth=.001) +
scale_y_continuous(trans = 'log10')
# recast the data
df1 <- recast(movies, value~., measure.var="rating")
names(df1) <- c("rating", "number")
# alternative way to recast data
df2 <- as.data.frame(table(movies$rating))
names(df2) <- c("rating", "number")
df2$rating <- as.numeric(as.character(df$rating))
# plot
p <- ggplot(df1, aes(x=rating)) + scale_y_continuous(trans="log10", name="density")
# with lines
p + geom_linerange(aes(ymax=number, ymin=.9))
# only points
p + geom_point(aes(y=number))