Histogram in R

Histogram in R

After a lot of finessing, code in R for a really great Histogram

 

R Ultimate Histogram

R Ultimate Histogram

 

library(ggplot2)

library(formattable)

library(scales)

# http://t-redactyl.io/blog/2016/02/creating-plots-in-r-using-ggplot2-part-7-histograms.html
windowsFonts(Tahoma=windowsFont(“Tahoma”))
lengthselect <- flist_widget[flist_widget$length==10,]
lengthselect

summary(lengthselect)

barfill <- “cyan3”
barlines <- “#1F3552”
meanprice <- mean(lengthselect$price)
medianprice <- currency(median(lengthselect$price), digits=0L)
sdprice <- currency(sd(lengthselect$price), digits=0L)
rangeprice <- currency(range(lengthselect$price), digits=0L)
minprice <- currency(min(lengthselect$price), digits=0L)
maxprice <- currency(max(lengthselect$price), digits=0L)

meanprice <- currency(meanprice, digits=0L)
meanprice

widgetlen1 <- ggplot(lengthselect, aes(x = price)) +
geom_histogram(aes(y = ..count..), binwidth = 250,
colour = barlines, fill = barfill, ) +

scale_x_continuous(name = “Price Bin”,
labels = dollar ,
breaks = seq(0, 9000, 2000),

#*** change the limits to ensure all data is included *****
limits=c(-500, 9500)) +

#*** change bin width size depending on the data *****
stat_bin(binwidth= 40, geom=”text”, aes(label = ifelse(..count.. > 0, ..count.., “”)), vjust = -0.5) +
scale_y_continuous(name = “Count”, labels=comma, limits=c(0, 200)) +
ggtitle(“Frequency Histogram of Widget”) +
theme_bw() +
theme(axis.line = element_line(size=1, colour = “black”),
panel.grid.major = element_line(colour = “#d3d3d3”),
panel.grid.minor = element_blank(),
panel.border = element_blank(), panel.background = element_blank(),
plot.title = element_text(size = 14, family = “Tahoma”, face = “bold”),
text=element_text(family=”Tahoma”),
axis.text.x=element_text(colour=”black”, size = 11),
axis.text.y=element_text(colour=”black”, size = 11)) +
geom_vline(xintercept = meanprice, size = 1, colour = “#FF3721”,
linetype = “dashed”) +

# *** change coordinates to ensure the annotated text is nicely positioned
annotate(“text”, x = 7500, y = 180,
label = (sprintf(“Mean value: %s\n Median value: %s\n Std. Dev: %s\n Min: %s\n Max: %s”, meanprice, medianprice, sdprice, minprice, maxprice )),colour=”darkblue” )

widgetlen1

Leave a Reply

%d bloggers like this: