Julia using StatsPlots.jl for grouped bar plot. How to get a legend on the bar plot? - julia

I'm trying to plot some data using Julia, but I'm quite new to Data visualisation in Julia. I have code that looks like this:
x_data = [5 10;
15 20]
groupedbar( ["0.2", "0.8"], x_data, xlabel = "X-axis",
ylabel="Y-axis")
Each x-value (0.2 and 0.8) will have 2 bars each which are different colours. I am trying to create a legend for these colours.
I have tried the following code but it for some reason plots the data incorrectly (only plots the first 2 data points):
groupedbar( ["0.2", "0.8"], x_data, xlabel = "X-axis",
ylabel="Y-axis", group = ["Category 1", "Category 2"])

Is this what you want?
groupedbar(["A", "A", "B", "B"], [4, 1, 2, 3], group = ["x", "y", "x", "y"])
(note that all three arguments have the same length)

Related

Plot with different colour variables and average line in R

I have a dataset in R of values in [-1,1] for 5 countries, namely (A,B,C,D,E) as follows:
data <- matrix(runif(n=50, min = -1, max = 1),ncol = 5)
data <- round(data,2)
colnames(data) <-
c("A", "B", "C", "D", "E")
Then I calculate the average value of each row for all countries with the following:
aver <- as.matrix(rowMeans(data))
rownames(aver) <- c("X1","X2","X3","X4","X5","X6","X7","X8","X9","X10")
I want to create a plot with the observations with each country (column) to have different colors and the aver line to be included. I am using the following but can not make it properly work.
plot(c(data),col=c("red","yellow","green","blue","black"))
lines(aver)
The final result must look like this but with colored observations included:
How can I do that??
Maybe you want something like this:
matplot(as.data.frame(data),col=c("red","yellow","green","blue","black"), pch=16, ylab = "")
lines(aver)
Output:
Add this for legend:
legend("bottomright", legend = colnames(data)[1:5], col=c("red","yellow","green","blue","black"), pch = 16)
Output:

How to display the values of every single bar in a barplot in R (without using ggplot)?

I am a beginner in R and thanks to the provided help here so far, I managed to create the following Barplot by using the code below. However, one issue is still open and I couldn't resolve it so far, even after reading all the answers provided in similar questions.
Code:
res <- data.frame( aggregate( rentals ~ weatherCond + season, bikes, sum ))
res$weatherCond <- ordered(res$weatherCond,
levels = c(1, 2, 3, 4),
labels = c("Clear", "Fog", "Snow", "Storm"))
res$season <- factor(res$season,
levels = c(1, 2, 3, 4),
labels = c("Winter", "Spring", "Summer", "Autumn"))
par(mar=c(10,4,2,1)+.5)
barplot(res[,"rentals"], names=apply( res[,1:2], 1, function(x) paste0(x[1],"_",x[2]) ), las=3, main = "Weather and Rentals", ylab = "Rentals", col = c('blue', 'red', 'green', 'grey')[res$weatherCond])
The plot visualizes the connection between the number of RENTED bikes and the SEASONs depending on the WEATHER conditions (3 variables). The bars in the plot show the amount of bikes RENTED, separated into the corresponding SEASON/WEATHER combinations.
My question:
how exactly should I modify the code above so that the count of the value of every single bar can be displayed (in the bar or on top of the bar)? Every single bar represents the number of rentals.
UPDATE:
I managed to display the values by adding the following lines of code:
y <- as.matrix(res$rentals)
text(b, y+2, labels=as.character(y)) <!-- the "b" is the barplot -->
However, the result is horrifying. Is there a way to make it look better?
barplot() returns the midpoints of each bar (see ?barplot). This can be used in combination with the function text() to display the numbers.
I your case, it would become:
mid_points <- barplot(res[,"rentals"], ...)
text(x = mid_points, y = res[,"rentals"], text = res[,"rentals"])
Further parameters can be used the modify the placement of the numbers.
Since I don't have your data, I used a modified base R example:
b <- barplot(GNP ~ Year, data = longley, ylim = c(0, 700))
text(
x = b,
y = longley$GNP,
labels = round(longley$GNP, 1),
pos = 3,
srt = 90,
offset = 1.5
)

Deviation chart in base graphics

I need to do a deviance chart (lollipop chart with lines from the mean to values above / below the mean). From this question and answer Drawing line segments in R, it is clear that I need to plot segments and then add the points. However, my x axis is a factor and the solution fails.
This works:
df <- data.frame(ID = c(1, 2, 3),
score = c(30, 42, 48))
mid <- mean(df$score)
plot(range(df$ID), range(df$score),type="n")
segments(df$ID, df$score, df$ID, mid)
But changing my identifier variable into a factor breaks it.
df$ID2 <- factor(df$ID)
plot(range(df$ID2), range(df$score),type="n")
segments(df$ID2, df$score, df$ID2, mid)
How can I set up the plot area and x-axis values to deal with a factor?
Note that I need a base graphics solution to fit with the other charts in a dashboard style report.
You can convert the factor in a numeric variable, supress the x-axis and then add the correct labels to the plot:
df$ID2 <- factor(letters[df$ID]) # Use letters to show that this is working
plot(range(as.numeric(df$ID2)), range(df$score), type = "n", xaxt = "n")
segments(as.numeric(df$ID2), df$score, as.numeric(df$ID2), mid)
axis(1, at = seq_along(levels(df$ID2)), labels = levels(df$ID2))

R horizontal barplot with axis labels split between two axis

I have a horizontal barplot, with zero in the middle of the x-axis and would like the name for each bar to appear on the same side as the bar itself. The code I am using is:
abun<-data$av.slope
species<-data$Species
cols <- c("blue", "red")[(abun > 0)+1]
barplot(abun, main="Predicted change in abundance", horiz=TRUE,
xlim=c(-0.04,0.08), col=cols, names.arg=species, las=1, cex.names=0.6)
I have tried creating two separate axes and the names do appear on the desired side for each bar, but are not level with the appropriate bar. I will try and upload an image of the barplot, am still very new to R, apologies if I am missing something basic!
barplot1- names in correct position but all on one axis
barplot2- names on both sides of plot but not in line with appropriate bar
We can accomplish this using mtext:
generate data
Since you didn't include your data in the question I generated my own dummy data set. If you post a dput of your data, we could adapt this solution to your data.
set.seed(123)
df1 <- data.frame(x = rnorm(20),
y = LETTERS[1:20])
df1$colour <- ifelse(df1$x < 0, 'blue', 'red')
make plot
bp <- barplot(df1$x, col = df1$colour, horiz = T)
mtext(side = ifelse(df1$x < 0, 2, 4),
text = df1$y,
las = 1,
at = bp,
line = 1)

Inserting a tick mark, as well as xlab in a barplot panel in r

I would like to include tick marks in addition to xlab in a 3 by 3 panel of bar plots. I tried this solution for a single graph, but somehow I had trouble replicating it. The idea is to label each of the bars with d that runs from -3 to +3, with a unit increase. The first bar in each plot represents the value of -3. I tried to demonstrate my problem with a simulated data below. Any ideas?
# Data generation
# Populating a matrix
matrix(rnorm(63, 1:9), nrow=7, byrow=TRUE)
# Labelling the matrix
colnames(mat.s) <- c("Hs", "Sex", "Es", "Bo", "R", "W", "S", "Pri", "Abo")
# Tick mark indicator
d <- seq(-3,3,1)
# Plotting estimates
par(mfrow=c(3,3), mar = c(4,3,3,1))
for(i in 1:9) {
# Bar plot
barplot(mat.s[,i],
# X-label
xlab = colnames(mat.s)[i])
}
Specify the axis.lty, names.arg and mgp inside the barplot function in the loop and you ll be fine:
#I haven't changed anything else before the for-loop
#only changes have taken place inside the barplot function below
for(i in 1:9) {
# Bar plot
barplot(mat.s[,i], xlab = colnames(mat.s)[i],
names.arg= as.character(-3:3), axis.lty=1, mgp=c(3,1,0.2))
}
Output:
In a bit more detail:
names.arg will add the labels
axis.lty=1 will add an x-axis
mgp is a vector of length three that controls the margins of the title, the labels and the axis line in this order. I only needed to change the third element of that to 0.2 so that the axis looks nice (check ?par).
An alternative to LyzandeR's excellent answer is to add axis() after assigning the barplot() call to an object:
for(i in 1:9) {
# Bar plot
temp <- barplot(mat.s[,i],
# X-label
xlab = colnames(mat.s)[i])
axis(1,at=temp,labels=-3:3)
}
Here's a ggplot version:
library(dplyr)
library(reshape2)
library(ggplot2)
# Add x-labels and reshape to long format then plot
ggplot(mat.s %>% mutate(x=-3:3) %>% melt(id.var="x"),
aes(x=x, y=value)) +
geom_bar(stat="identity", fill=hcl(195,100,65)) +
facet_wrap(~variable) +
labs(x="", y="") +
scale_x_continuous(breaks=-3:3)

Resources