data visualization - How to combine different barplot in R? -
i new r user.
i have difficult time figuring out how combine different barplot 1 graph.
for example,
suppose, top 5 of professions in china, are, government employees, ceos, doctors, athletes, artists, incomes (in dollars) respectively, 20,000,17,000,15,000,14,000,and 13,000, while top 5 of professions in us, are, doctors, athletes, artists, lawyers, teachers incomes (in dollars) respectively, 40,000,35,000,30,000,25,000 , 20,000.
i want show differences in 1 graph.
how supposed that? beware have different names.
the answer question straight forward. new r user, recommend make liberal use of 'ggplot2' package. many r users, 1 package enough.
to "combined" barchart described in original post, answer put of data 1 dataset , add grouping variables, so:
step 1: make dataset.
data <- read.table(text=" country,profession,income china,government employee,20000 china,ceo,17000 china,doctor,15000 china,athlete,14000 china,artist,13000 usa,doctor,40000 usa,athlete,35000 usa,artist,30000 usa,lawyer,25000 usa,teacher,20000", header=true, sep=",")
you'll notice i'm using 'read.table' function here. not required , purely readability in example. important part have our values (income) , our grouping variables (country, profession).
step 2: create barchart income height of bars, profession x-axis, , color bars country.
library(ggplot2) ggplot(data, aes(x=profession, y=income, fill=country)) + geom_bar(stat="identity", position="dodge") + theme(axis.text.x = element_text(angle = 90))
here first loading 'ggplot2' package. may need install this.
then, specify data want use , how separate it.
ggplot(data, aes(x=profession, y=income, fill=country))
this tells 'ggplot' use our dataset in 'data' data frame. aes()
command specifies how 'ggplot' should read data. map grouping variable income onto x-axis, map income onto y-axis, , change color (fill) of each bar according grouping variable country.
next, specify kind of barchart want.
geom_bar(stat="identity", position="dodge")
this tells 'ggplot' make barchart (geom_bar()
). default, 'geom_bar' function tries make histogram, have totals want use. tell use our totals specifying type of statistic represented in income total, or actual values (identity) want chart (stat="identity"
). finally, made judgement call how display data , decided set 1 set of data on next other when single profession has multiple income values (position="dodge"
).
finally, need rotate x-axis labels, since of them quite long. simple 'theme' command changes rotation of x-axis text elements.
theme(axis.text.x = element_text(angle = 90))
we chain of these commands +
, , it's done!
Comments
Post a Comment