R - converting a table to data frame - r

I'm working on the Titanic dataset from R. I want to analyse the dataset using a ggplot (stacked and group bar plots). So I wanted to convert the table into a data-frame so I could plot the graphs. I used the following code to convert :
df<-as.data.frame(Titanic)
View(df)
However, even on viewing I see my df to be more like a data-table.
And further when I tried to use it to plot a function usinf the code:
ggplot(data=df) + geom_bar(aes(x=Class,y=Sex))
All it shows is an empty plot, with just the labels on x and y axis, along with the categorical values of Sex as Male & Female and Class as 1st,2nd,3rd and crew.
What confuses me even more is that it's picking up the categorical values from the dataset but not the observations.
Please let me know how I can convert to dataframe correctly. Thanks :)

If I reproduce your code it gives me this error:
Error : Mapping a variable to y and also using stat="bin".
This is because you also included the y=Sex in your script. The main question therefore is, what would you like to plot?
If this is a barchart with the count of persons in each class the code will be:
ggplot(data=df) + geom_bar(aes(x=Class))
If it will be the total amount of females/males it will be:
ggplot(data=df) + geom_bar(aes(x=Sex))
Do not try to plot them at the same time.
To get back to the question. There is nothing wrong with your data frame. It is your ggplot code that is faulty.

Related

How to plot a gg barplot for a single factor column?

My data frame has 621 rows and each column describes something about it. I'm trying to do a exploratory data analysis where I plot out all the data into a bar plot.
I have a factor column called phenotype, which has 86 levels which describe the main condition in my cohort. I want to plot this out as 86 separate bar plots, each with the total number of people who have that condition on ggplot.
I've attached a screenshot of my data below, I basically want the x axis to have the condition name like the 'Bardet-Biedl Syndrome', 'Classic Ehlers Danlos Syndrome' etc and on the y axis the number of people who have that condition, such as 3,4,5 as displayed below etc. I got the below data by basically doing
table(data.frame$Phenotype)
I'm using the below code to generate my ggplot
ggplot (tiering, aes(x = Phenotype, y = count(tiering$Phenotype))) +
theme bw() +
geom bar(stat = "identity")
I'm sure the answer is out there, but I've looked on the R help websites and I can't seem to figure this out, so would be very grateful for the help.
EDIT: I got to a marplot with the help of the below code, just trying to reorder the bar/columns in decreasing order and tried this method but it hasn't worked. Would anyone have any suggestions?

Creating a multi-panel plot of a data set grouped by two grouping variables in R

I'm trying to solve the following exercise:
Make a scatter plot of the relationship between the variables 'K1' and 'K2' with "faceting" based on the parameters 'diam' and 'na' (subdivide the canvas by these two variables). Finally, assign different colors to the points depending on the 'thickness' of the ring (don't forget to factor it before). The graph should be similar to this one ("grosor" stands by "thickness"):
Now, the last code I tried with is the following one (the dataset is called "qerat"):
ggplot(qerat, aes(K1,K2, fill=factor(grosor))) + geom_point() + facet_wrap(vars(diam,na))
¿Could somebody give me a hand pointing out where the mistake is? ¡Many thanks in advance!
Maybe you are looking for a facet_grid() approach. Here the code using a data similar to yours:
library(ggplot2)
#Data
data("diamonds")
#Plot
ggplot(diamonds,aes(x=carat,y=price,color=factor(cut)))+
geom_point()+
facet_grid(color~clarity)
Output:
In the case of your code, as no data is present, I would suggest next changes:
#Code
ggplot(qerat, aes(K1,K2, color=factor(grosor)))+
geom_point() +
facet_grid(diam~na)

Density plot for multiple group shows one line, however legend shows 3

I am analyzing US election data volume from Google trend. I type the below command in R studio.
The poliData dataframe contains the SearchVolume for all months for three Politicians.
ggplot(data = poliData, aes(x=Date, group=Politician, colour=Politician)) +
geom_density()
But I only get the density line (blue) for one politician only with the above command.See the attached picture. Can you please help
I guess you got three lines on top each other because Date variable values are the same for all three politicians. My understanding of your analysis could be something like this:
ggplot(data = poliData,
aes(x=Date, colour=Politician,
weight = SearchVolume/sum(SearchVolume))) +
geom_density()
Adding weight should produce distinct lines for different politicians. If this is not what you wanted, please dput your data for others to work out a solution for you. Also, as I do not have the data, I have not tested the above code yet. Please let me know if it does not work.

simple boxplot using qplot/ggplot2

This is my first post, so go easy. Up until now (the past ~5 years?) I've been able to either tweak my R code the right way or find an answer on this or various other sites. Trust me when I say that I've looked for an answer!
I have a working script to create the attached boxplot in basic R.
http://i.stack.imgur.com/NaATo.jpg
This is fine, but I really just want to "jazz" it up in ggplot, for vain reasons.
I've looked at the following questions and they are close, but not complete:
Why does a boxplot in ggplot requires axis x and y?
How do you draw a boxplot without specifying x axis?
My data is basically like "mtcars" if all the numerical variables were on the same scale.
All I want to do is plot each variable on the same boxplot, like the basic R boxplot I made above. My y axis is the same continuous scale (0 to 1) for each box and the x axis simply labels each month plus a yearly average (think all the mtcars values the same on the y axis and the x axis is each vehicle model). Each box of my data represents 75 observations (kind of like if mtcars had 75 different vehicle models), again all the boxes are on the same scale.
What am I missing?
Though I don't think mtcars makes a great example for this, here it is:
First, we make the data (hopefully) more similar to yours by using a column instead of rownames.
mt = mtcars
mt$car = row.names(mtcars)
Then we reshape to long format:
mt_long = reshape2::melt(mt, id.vars = "car")
Then the plot is easy:
library(ggplot2)
ggplot(mt_long, aes(x = variable, y = value)) +
geom_boxplot()
Using ggplot all but requires data in "long" format rather than "wide" format. If you want something to be mapped to a graphical dimension (x-axis, y-axis, color, shape, etc.), then it should be a column in your data. Luckily, it's usually quite easy to get data in the right format with reshape2::melt or tidyr::gather. I'd recommend reading the Tidy Data paper for more on this topic.

Plotting multiple time-series in ggplot

I have a time-series dataset consisting of 10 variables.
I would like to create a time-series plot, where each 10 variable is plotted in different colors, over time, on the same graph. The values should be on the Y axis and the dates on the X axis.
Click Here for dataset csv
This is the (probably wrong) code I have been using:
c.o<-read.csv(file="co.csv",head=TRUE)
ggplot(c.o, aes(Year, a, b, c, d, e,f))+geom_line()
and here's what the output from the code looks like:
Can anyone point me in the right direction? I wasn't able to find anything in previous threads.
PROBLEM SOLVED, SEE BELOW.
One additional thing I would like to know:
Is it possible to add an extra line to the plot which represents the average of all variables across time, and have some smoothing below and above that line to represent individual variations?
If your data is called df something like this:
library(ggplot2)
library(reshape2)
meltdf <- melt(df,id="Year")
ggplot(meltdf,aes(x=Year,y=value,colour=variable,group=variable)) + geom_line()
So basically in my code when I use aes() im telling it the x-axis is Year, the y-axis is value and then the colour/grouping is by the variable.
The melt() function was to get your data in the format ggplot2 would like. One big column for year, etc.. which you then effectively split when you tell it to plot by separate lines for your variable.

Resources