I need help with a bar chart in R. I did not find exactly what I was looking for using the search function.
I have to compare the European unemployment rate in an empirical work. I managed to get the basic structure right. Unfortunately, I didn't manage to get the corresponding values behind the horizontal bars. I have attached a picture of what it should look like in the end (red values)
options(stringsAsFactors = F)
ewq<- read.table(file='Europa.txt', header=TRUE, sep = ';')
attach(ewq)
par(mar=c(5,10,2,2))
barplot(Wert3, names.arg = Land,
horiz=T,
main= "Erwerbslosenquote in ausgewählten EU-Ländern",
cex.names=0.8,
xlim=c(0,20),
ylim=c(0,19),
col= c("honeydew3", "honeydew3","honeydew3","honeydew3","azure","honeydew3",
"honeydew3","honeydew3","honeydew3","honeydew3","honeydew3","honeydew3",
"honeydew3","honeydew3","deeppink","honeydew3"),
xlab= "Erwerbslosenquote in Prozent [Stand: Okt. 2019]",
las=1)
My Data:
Land;Wert3
Griechenland (EU-Max);16.7
Spanien;14.2
Italien;9.7
Frankreich;8.5
Europa;6.8
Schweden;6.8
Portugal;6.5
Litauen;6.4
Irland;4.8
Österreich;4.6
Rumänien;4
Vereinigtes Königreich;3.8
Niederlande;3.5
Polen;3.2
Deutschland;3.1
Tschechien (EU-Min);2.2
This is what it should look like
This is my dataframe
Maybe you also have a tip how I could solve the thing with the colors more elegantly. But it's not that important :-D
I don't know if it's relevant, but I use R-Studio on the macOS Catalina. Thanks a lot!( Sorry, I'm not an expert at all!:) )
I can only try it for 5 of your values, but it should work for all your data.
Land<-c("Spanien", "Italien", "Europa", "Deutschland", "Polen")
Wert3<-c(14.2, 9.7, 6.8, 3.2, 3.1)
We set the colors, if Europa make it azure, if Deutschland deeppink
COLS = rep("honeydew3",length(Land))
COLS[Land=="Europa"] = "azure"
COLS[Land=="Deutschland"] = "deeppink"
I need to set the par() to see the labels, but ignore it if you can see the labels. Key is to save the barplot
par(mar=c(5,5,5,5))
BAR = barplot(Wert3, names.arg = Land,
horiz=T,
main= "Erwerbslosenquote in ausgewählten EU-Ländern",
cex.names=0.8,
xlim=c(0,20),
ylim=c(0,6),
col= COLS,
xlab= "Erwerbslosenquote in Prozent [Stand: Okt. 2019]",
las=1)
text(x=Wert3+2,y=BAR,Wert3,col="red",cex=0.7)
Related
I made the following histogram. I want to display a stats box with a border here, like the image on this sites image, and write various information there. In addition, it is assumed that you will also write legends for multiple histograms.
As a result of research, I found that ROOT has a similar function, but I would like to realize this with R. How can I do this with R?
The xlsx file I used is large, so I uploaded it here.
library(readxl)
file = read_excel("./data.xlsx")
summary(file)
data = file[["foo[%]"]]
par(las=1, family="Century gothic", xaxs="i", yaxs="i", cex.main=3, cex.lab=1.1, cex.axis=1.1, font.lab=2, font.axis=2)
h = hist(data, yaxt="n", tck=0.03, breaks=seq(18,18.35,0.01), main=NA, xlab="xaxis", ylab="freq", border=NA, col="#00000000", ylim=c(0,100))
axis(2, tck=0.03, at=c(0,10,20,30,40,50,60,70,80,90,100))
grid()
lines(rep(h$breaks, each=2)[-c(1,2*length(h$breaks))], rep(h$counts, each=2), lwd=3)
box()
#jay.sf's suggestion is a little tricky to implement. Here's an example that comes close, but it's not perfect: the spacing is wrong. Maybe someone can improve it?
statname <- expression("Entries", "Mean", "Std Dev", chi^2/"ndf", "Prob", "Constant", "Slope")
statvalue <- expression(5000, 19.59, 18.61, 131.1/115, 0.1447, 5.54 %+-% 0.04,
-0.0514 %+-% 0.0011)
plot(1)
legend("topright", title = "hB",
legend = c(statname, statvalue),
ncol = 2,
x.intersp = 0)
Created on 2021-02-21 by the reprex package (v0.3.0)
It uses expression() for the entries because you have math in them; you might be able to do it reasonably well with special characters instead. I couldn't find a way to set the spacing of the two columns differently: your example had the names flush left and the values flush right. Nor could I set the column widths separately. Probably if you really want to fine tune this, you'll have to write your own function based on the legend function.
I'm really new in R statistics and i just bumped into a problem when it comes to creating a box plot. I have used the following script that i have created:
# Reset R's braingetwd
rm(list=ls())
# Tells R where to look
setwd("/Users/Axel/Desktop/Kandidatarbete/Data")
# Confirms R is looking at the right place
getwd()
# Read data
read.table("migration_test_graph.txt")
# Assign a name to the data
migrationtest5<- read.table("migration_test_graph.txt", ,col.names=c('treatment','migration'), header=TRUE, sep="\t", na.strings="NA", dec=",", strip.white=TRUE)
mzmz=migrationtest5[which(migrationtest5$treatment == "MzMz"),]
mzct=migrationtest5[which(migrationtest5$treatment == "MzCt"),]
ctct=migrationtest5[which(migrationtest5$treatment == "CtCt"),]
ctmz=migrationtest5[which(migrationtest5$treatment == "CtMz"),]
#plot data (migration in function of index)
boxplot(migration~treatment, data=migrationtest5, boxwex=0.5, varwidth=TRUE, staplewex=FALSE, outline=TRUE, outpch=20, cex= 0.3, range=1, title=FALSE, whisklty=19, col=c("darkolivegreen","darkolivegreen","darkolivegreen3", "darkolivegreen3"), xlab="", ylab="Migration index", las=1, ylim=c(0, 1), cex.lab=1, cex.axis=0.75, axes=FALSE, border=NA, medcol="white", whiskcol="black", outcol="black", whisklwd=2, medlwd=4)
axis(1, at=seq(0, 5, by=1), cex.axis=1, labels=c("", "CtCt","MzCt", "CtMz", "MzMz",""), lwd=2)
axis(2, at=seq(0,1, by=0.2), las=2, cex.axis=1, lwd=2)
The problem is that the whole graph looks skew and the data are located on the wrong places. Anyone got a clue what might be the problem? The big box plots are supposed to be located above the CtMz and MzMz and the small ones above the MzCt and CtCt.
Thanks in advance
Axel
Hoping for some pointers or some experiences insight as i'm literally losing my mind over this, been trying for 2 full days to set up the right values to have a function spit out clean simple line plots from the gbm.plot function (packages dismo & gbm).
Here's where I start. bty=n in par to turn off the box & leave me with only left & bottom axes. Gbm.plot typically spits out one plot per explanatory variable, so usually 6 plots etc, but I'm tweaking it to do one per variable & looping it. I've removed the loop & lots of other code so it's easy to see what's going on.
png(filename = "whatever.png",width=4*480, height=4*480, units="px", pointsize=80, bg="white", res = NA, family="", type="cairo-png")
par(mar=c(2.6,2,0.4,0.5), fig=c(0,1,0.1,1), las=1, bty="n", mgp=c(1.6,0.5,0))
gbm.plot(my_gbm_model,
n.plots=1,
plot.layout = c(1,1),
y.label = "",
write.title=F,
variable.no = 1, #this is part of the multiple plots thing, calls the explanatory variable
lwd=8, #this controls the width of the main result line ONLY
rug=F)
dev.off()
So this is what the starting condition looks like. Aim: make the axes & ticks thicker. That's it.
Putting "lwd=20" in par does nothing.
Adding axes=F into gbm.plot() turns the axes and their numbers off. So I conclude that the control of these axes is handled by gbm.plot, not par. Here's where it get's frustrating and crap. Accepted wisdom from searches says that lwd should control this but it only controls the wiggly centre line as per my note above. So maybe I could add axis(side=1, lwd=8) into gbm.plot() ?
It runs but inexplicably adds a smoother! (which is very thin & hard to see on the web but it's there, I promise). It adds these warnings:
In if (smooth & is.vector(predictors[[j]])) { ... :
the condition has length > 1 and only the first element will be used
Fine, R's going to be a dick for seemingly no reason, I'll keep plugging the leaks as they come up. New code with axis as before and now smoother turned off:
png(filename = "whatever.png",width=4*480, height=4*480, units="px", pointsize=80, bg="white", res = NA, family="", type="cairo-png")
par(mar=c(2.6,2,0.4,0.5), fig=c(0,1,0.1,1), las=1, bty="n", mgp=c(1.6,0.5,0))
gbm.plot(my_gbm_model,
n.plots=1,
plot.layout = c(1,1),
y.label = "",
write.title=F,
variable.no = 1,
lwd=8,
rug=F,
smooth=F,
axis(side=1,lwd=8))
dev.off()
Gives error:
Error in axis(side = 1, lwd = 8) : plot.new has not been called yet
So it's CLEARLY drawing axes within plot since I can't affect the axes from par and I can turn them off in plot. I can do what I want and make one axis bold, but that results in a smoother and warnings. I can turn the smoother off, but then it fails because it says plot.new hadn't been called. And this doesn't even account for the other axis I have to deal with, which also causes the plot.new failure if I call 2 axis sequentially and allow the smoother.
Am I the butt of a big joke here, or am I missing something obvious? It took me long enough to work out that par is supposed to be before all plots unless you're outputting them with png etc in which case it has to be between png & plot - unbelievably this info isn't in ?par. I know I'm going off topic by ranting, sorry, but yeah, 2 full days. Has this been everyone's experience of plotting in R?
I'm going to open the vodka in the freezer. I appreciate I've not put the full reproducible code here, apologies, I can do if absolutely necessary, but it's such a huge timesuck to get to reproducible stage and I'm hoping someone can see a basic logical/coding failure screaming out at them from what I've given.
Thanks guys.
EDIT: reproducibility
core data csv: https://drive.google.com/file/d/0B6LsdZetdypkWnBJVDJ5U3l4UFU
(I've tried to make these data reproducible before and I can't work out how to do so)
samples<-read.csv("data.csv", header = TRUE, row.names=NULL)
my_gbm_model<-gbm.step(data=samples, gbm.x=1:6, gbm.y=7, family = "bernoulli", tree.complexity = 2, learning.rate = 0.01, bag.fraction = 0.5))
Here's what will widen your axis ticks:
..... , lwd.ticks=4 , ...
I predict on the basis of no testing because I keep getting errors with what limited code you have provided) that it will get handled correctly in either gbm.plot or in a subsequent axis call. There will need to be a subsequent axis call, two of them in fact (because as you noted 'lwd' gets passed around indiscriminately):
png(filename = "whatever.png",width=4*480, height=4*480, units="px", pointsize=80, bg="white", res = NA, family="", type="cairo-png")
par(mar=c(2.6,2,0.4,0.5), fig=c(0,1,0.1,1), las=1, bty="n", mgp=c(1.6,0.5,0))
gbm.plot(my_gbm_model,
n.plots=1,
plot.layout = c(1,1),
y.label = "",
write.title=F,
variable.no = 1,
lwd=8,
rug=F,
smooth=F, axes="F",
axis(side=1,lwd=8))
axis(1, lwd.ticks=4, lwd=4)
# the only way to prevent `lwd` from also affecting plot line
axis(2, lwd.ticks=4, lwd=4)
dev.off()
This is what I see with a simple example:
png(); Speed <- cars$speed
Distance <- cars$dist
plot(Speed, Distance,
panel.first = lines(stats::lowess(Speed, Distance), lty = "dashed"),
pch = 0, cex = 1.2, col = "blue", axes=FALSE)
axis(1, lwd.ticks=4, lwd=4)
axis(2, lwd.ticks=4, lwd=4)
dev.off()
I have several carbon compounds in my bar graph but I need to subscript the numbers associated with each one, e.g. C*12*-C*16*, C*17*-C*25*,C*26*-C*32*,C*33*-C*37*.
I am trying to use the expression function but it is not going well with the names.arg function on barplot. Please see the code so far:
barplot(t(as.matrix(alkane)),
ylim=c(0,100),
names.arg=c("C12-C16","C17-C25","C26-C32","C33-C37"),
xlab="Hydrocarbons analysed after 21 days",
ylab="% loss in concentration relative to day 0",
cex.lab=0.8,
cex.axis=0.8,
cex.names=0.8,
cex.main=0.8,
beside=TRUE,
col=c("blue","red"))
Any help would be really appreciated.
I suppose you are looking for this:
set.seed(1)
x <- matrix(rbeta(8, 5, 5), 2, 4)
barplot(x, names.arg =
expression(C[12]-C[16], C[17]-C[25], C[26]-C[32],C[33]-C[37]))
As you can see with the highlighting it is not properly formatted your names.arg, check the " to be paired:
names.arg=c("C12-C16","C17-C25","C26-C32","C33-C37"),
I am attempting to create a bargraph in r, and I am having trouble with the x axis labels being cut off. However this is only happening when I save the graph to a file. If I print it to the graphics device it shows all of the labels, however when I save the file the labels are cut off.
Here is code that reproduces the problem.
Captivate<-51.38
Challenge<-88.88889
Clarify<-80.55556
Confer<- 81.29085
Consolidate<-64.81481
Care<-68.51852
Control<-70.66993
Engagement<-66.17239
df<-rbind(Captivate, Challenge, Clarify, Confer, Consolidate, Care, Control, Engagement)
png("~/graph.png")
barplot(df, beside=TRUE, ylim=c(0,100),ylab="Percentage of Positive Answers ", space=.1, main="Some Title",
names.arg=c("Captivate", "Challenge", "Clarify", "Confer", "Consolidate", "Care", "Control", "Engagement"), las=2, axis.lty=1)
dev.off()
I have tried changing the margins using par() however nothing has worked.
Can anyone tell me what I need to do to have the full labels showing?
Starting up a new graphics device resets the par values to the device defaults so you need to set mar after calling png:
png("~/graph.png") ; par(mar=c(6, 4, 4, 2) + 0.1)
barplot(df, beside=TRUE, ylim=c(0,100),
ylab="Percentage of Positive Answers ", space=.1, main="Some Title",
names.arg=c("Captivate", "Challenge", "Clarify", "Confer", "Consolidate", "Care", "Control", "Engagement"), las=2, axis.lty=1)
dev.off()