X-axis labels not printing on Base Plotting System On R - r

"R version 4.0.3 (2020-10-10)"
I have a some time-series data where I am trying to look at the change in consumption over time. Here is a reprex.
set.seed(1)
date <- seq(as.POSIXct('2010-01-01'),as.POSIXct('2010-04-10'),by=86400)
Consumption <- rnorm(99)
Data <- data.frame(date,Consumption)
plot(Data$Consumption~Data$date,type='l') # X-axis labels and ticks not printing
par(yaxt='n')
axis(side = 2,at=seq(-3,3,0.5),labels = seq(-3,3,0.5)) # This works on the first plot on the y axis
plot(Data$date~Data$Consumption,type='l') # X-axis refusing to print despite assigning it.
par(xaxt='n')
axis(side = 1,at=seq(-3,3,0.5),labels = seq(-3,3,0.5)) # This works on the first plot
The graph outputted in the initial plot() is exactly what I want except for the fact it doesn't have any labels for the x-axis.
I am using Base Plotting for an assignment rather than everyday use and would usually use ggplot.
I have been trying to figure out why the x-axis is not plotting. Initially I thought the problem was with the date variable and tried cleaning it up with lubridate::ymd(). However when I started making the above reprex for the purpose of this question it is clear to the X-axis labels and ticks as whole is not printing. In the second plot I put the consumption variable on the x-axis. I was surprised to find that the date is printing neatly on its own on the Y-axis.
What am I doing wrong?

When you want more control over what happens with axis labels and title, you could create them manually. So, first produce a plot without title and label. Then, create them manually with axis() and mtext(). In the process, you may increase the room at the bottom of the plot with par(mar=...). Finetuning is done with arguments like las, cex.axis, and line. And at the end, you reset mar to its old values.
You could use the code below to get more detailed X-axis labels
### format to day (probably not the best way to do this)
Data$date2 <-format(Data$date, "%d%b")
Data$date2 <- as.Date(Data$date2, format = "%d%b")
### increase room at bottom of the plot for X-axis title
### the labels will eat up space, if we do nothing it will be a mess
### set title with mtext later
par(mar = c(7,4,4,2))
### plot without X-axis labels (xaxt) and title (xlab)
### work with "at" and "labels" in axis-function
### rotate labels 90° (las) an reduce font (cex.axis)
### put title 5 lines below graph (line)
###
### Remark: the graph window has to be big enough
plot(Data$Consumption ~ Data$date, type= "l", xaxt = "n", xlab = NA)
axis(side = 1, at = Data$date, labels = Data$date2, las = 2, cex.axis=.75)
mtext(side = 1, text = "Date", line = 5)
This yields the following graph:
ALTERNATIVE
ticks and labels for every 7th item
per7 <- seq(1, 99, 7)
plot(Data$Consumption ~ Data$date, type= "l", xaxt = "n", xlab = NA)
axis(side = 1, at = Data$date[per7], labels = Data$date2[per7], las = 2, cex.axis=.75)
mtext(side = 1, text = "Date", line = 5)
### reset mar
par(mar = c(5,4,4,2))
which gives the following picture:
Please let me know whether this is what you wanted.

There are two issues I can see readily:
change: Consumption <- rnorm(99) to Consumption <- rnorm(100) to
match date column.
The problem is with 'par'. When there are multiple plots within a chunk, unlike ggplot, plot does not handle properly. Remove par and run the below it should work
set.seed(1)
date <- seq(as.POSIXct('2010-01-01'),as.POSIXct('2010-04-10'),by=86400)
Consumption <- rnorm(100)
Data <- data.frame(date,Consumption)
plot(Data$Consumption~Data$date,type='l')
plot(Data$date~Data$Consumption,type='l')
Please note whenever you define par and when you run each plot in two different chunks, the labels will display properly. You will not have any issue. But when you plot both the charts in a single chunk, you will always have problem if you have par.

Related

How do I get all my labels from x-axis shown on R for a barplot?

This is my first time using RStudio, and I've tried to find the the answer to my solution along with tinkering around with the code but I haven't been able to figure it out. I've even looked here and found other users with the same issue How to display all x labels in R barplot? and Rotating x axis labels in R for barplot but I wasn't able to get the answered solutions to work for my code. I've also asked two people more familiar with R, but after looking over my code and trying for themselves they were also unable to figure it out as well.
Everything would just result in error messages (I don't have the error messages showing in my console since when someone was trying to figure it out they cleared the global environment).
I have already generated 15 bars for my barplot, and the barplot itself is generated with the labels for the ylab, the title for my xlab, and the main, and I even have it colored, but I can't name each individual column bar.
The names for all the labels are listed in the source, but it's only showing every third bar or so. I need all bars labeled.
setwd("C:/Users/Person/Desktop/Rfolder")
library(readxl)
data <- read_excel("filename.xlsx")
View(topic)
barplot(data$'per hundred',
main ="Title",
xlab = "Words",
ylab = "variable stats",
col = c("gray"))
axis(1, at =c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15),
srt = 45,
labels=c("Apple","Butter","Banana","Bacon","Candy","Carrot","Spam","Ube","Ice cream","Italian ice","Jackfruit","Kale","Tofu","Udon","All types"))
Coded Food Barplot
Use las=2 to set labels from horizontal to vertical.
This one works, with working example added:
df <- cbind.data.frame("names" = c("Apple","Butter","Banana","Bacon","Candy","Carrot","Spam","Ube","Ice cream","Italian ice","Jackfruit","Kale","Tofu","Udon","All types"), "numbers" = sample(20:100, 15))
barplot(height = df$numbers,
names.arg = df$names,
main = "Title",
xlab = "Words",
ylim = c(0, 100),
ylab = "variable stats",
col = c("gray"),
las = 2)
To modify sizing of x axis names and labels, add options:
cex.names = 1 # controls magnification of x axis names. value starts at 1
cex.lab = 1 # control magnification of x & y axis labels. value starts at 1
to the barplot() function. Play around with sizing to find what works for you best. To escape the overlap of x axis label and x axis names, instead of xlab = "Words" use sub = "Words". Simple & efficient.
Here's the barplot generated with all the labels.
Food Labeled Barplot

Base Plot, correctly defining axis [duplicate]

How can I change the spacing of tick marks on the axis of a plot?
What parameters should I use with base plot or with rgl?
There are at least two ways for achieving this in base graph (my examples are for the x-axis, but work the same for the y-axis):
Use par(xaxp = c(x1, x2, n)) or plot(..., xaxp = c(x1, x2, n)) to define the position (x1 & x2) of the extreme tick marks and the number of intervals between the tick marks (n). Accordingly, n+1 is the number of tick marks drawn. (This works only if you use no logarithmic scale, for the behavior with logarithmic scales see ?par.)
You can suppress the drawing of the axis altogether and add the tick marks later with axis().
To suppress the drawing of the axis use plot(... , xaxt = "n").
Then call axis() with side, at, and labels: axis(side = 1, at = v1, labels = v2). With side referring to the side of the axis (1 = x-axis, 2 = y-axis), v1 being a vector containing the position of the ticks (e.g., c(1, 3, 5) if your axis ranges from 0 to 6 and you want three marks), and v2 a vector containing the labels for the specified tick marks (must be of same length as v1, e.g., c("group a", "group b", "group c")). See ?axis and my updated answer to a post on stats.stackexchange for an example of this method.
With base graphics, the easiest way is to stop the plotting functions from drawing axes and then draw them yourself.
plot(1:10, 1:10, axes = FALSE)
axis(side = 1, at = c(1,5,10))
axis(side = 2, at = c(1,3,7,10))
box()
I have a data set with Time as the x-axis, and Intensity as y-axis. I'd need to first delete all the default axes except the axes' labels with:
plot(Time,Intensity,axes=F)
Then I rebuild the plot's elements with:
box() # create a wrap around the points plotted
axis(labels=NA,side=1,tck=-0.015,at=c(seq(from=0,to=1000,by=100))) # labels = NA prevents the creation of the numbers and tick marks, tck is how long the tick mark is.
axis(labels=NA,side=2,tck=-0.015)
axis(lwd=0,side=1,line=-0.4,at=c(seq(from=0,to=1000,by=100))) # lwd option sets the tick mark to 0 length because tck already takes care of the mark
axis(lwd=0,line=-0.4,side=2,las=1) # las changes the direction of the number labels to horizontal instead of vertical.
So, at = c(...) specifies the collection of positions to put the tick marks. Here I'd like to put the marks at 0, 100, 200,..., 1000. seq(from =...,to =...,by =...) gives me the choice of limits and the increments.
And if you don't want R to add decimals or zeros, you can stop it from drawing the x axis or the y axis or both using ...axt. Then, you can add your own ticks and labels:
plot(x, y, xaxt="n")
plot(x, y, yaxt="n")
axis(1 or 2, at=c(1, 5, 10), labels=c("First", "Second", "Third"))
I just discovered the Hmisc package:
Contains many functions useful for data analysis, high-level graphics, utility operations, functions for computing sample size and power, importing and annotating datasets, imputing missing values, advanced table making, variable clustering, character string manipulation, conversion of R objects to LaTeX and html code, and recoding variables.
library(Hmisc)
plot(...)
minor.tick(nx=10, ny=10) # make minor tick marks (without labels) every 10th

How to plot actual year in x axis of r plot instead of year 0,1,2......20

I am newbie in R. please show me the correct link if I asked my question in wrong forum. I am reading and extracting data from netcdf file. I want to plot actual year i.e. 1980,1981,......1999 in x-axis instead of 0,1,...20. I tried to change the range using xrange or xaxt and axis command in plot but unable to do so.Also, I want to plot the lines between 1980-1999 buthttp://i.stack.imgur.com/z8sEL.png the line continues after 1999 (see image) I tried since last 7 days without any succes and could not concentrate and move on. I have copied partial code and image. I will appreciate your help. Thank you.
for (j in 1:length(station_rchid)){
for (i in 1:length(rchid)){
if(identical(station_rchid[j],rchid[i])){
windows()
per<-'Average Annual '
an_time<-1:nyear
heading <- paste(per,vari,tper,station_name[j])
yrange<- max(varX_year[1,,j],varX_year[2,,j])
plot(an_time,varX_year[1,,j],main=heading,type="l",ylim=c(0,yrange),xlab="Year",ylab=unity,col="red",cex.lab=1.5,cex.axis=1.5)
lines(an_time,varX_year[2,,j],col="blue")
legend("topleft", c("Pred","Obs"),lty=c(1,1),lwd=c(2.5,2.5), col=c("red","blue"),inset = 1.4)
filename<-paste("NZ_Annual_swe_",station_name[i],".xls")
# write.xls(varX_year[ , ,j],file=filename,colNames=TRUE,rowNames=FALSE)
One way is to remove the axes in the plot and then re-add them later. The pretty can help you automate the label placements. Parse all axis-options to the axis lines.
plot(an_time, varX_year, main = heading, type="l", ylim = c(0,yrange)
,xlab = "Year", ylab = unity, col = "red", cex.lab = 1.5,
,axes = FALSE)
axis(1, at = pretty(an_time), labels = pretty(an_time) + 1980, cex.axis=1.5)
axis(2, cex.axis=1.5,)
box()
Be cautious with this approach, since you only change the labels.
Another workaround I suppose could be just to add 1980 to the year vector, i.e.
an_time <- an_time + 1980

change distance of x-axis labels from axis in sciplot bargraph

I'm constructing a plot using bargraph.CI from sciplot. The x-axis represents a categorical variable, so the values of this variable are the names for the different positions on the x-axis. Unfortunately these names are long, so at default settings, some of them just disappear. I solved this problem by splitting them into multiple lines by injecting "\n" where needed. This basically worked, but because the names are now multi-line, they look too close to the x-axis. I need to move them farther away. How?
I know I can do this with mgp, but that affects the y-axis too.
I know I can set axisnames=FALSE in my call to barplot.CI, then use axis to create a separate x-axis. (In fact, I'm already doing that, but only to make the x-axis extend farther than it would by default- see my code below.) Then I could give the x-axis its own mgp parameter that would not affect the y-axis. But as far as I can tell, axis() is well set up for ordinal or continuous variables and doesn't seem to work great for categorical variables. After some fiddling, I couldn't get it to put the names in the right locations (i.e. right under their correspondence bars)
Finally, I tried using mgp.axis.labels from Hmisc to set ONLY the x-axis mgp, which is precisely what I want, but as far as I could tell it had no effect on anything.
Ideas? Here's my code.
ylim = c(0.5,0.8)
yticks = seq(ylim[1],ylim[2],0.1)
ylab = paste(100*yticks,"%",sep="")
bargraph.CI(
response = D$accuracy,
ylab = "% Accuracy on Test",
ylim = ylim,
x.factor = D$training,
xlab = "Training Condition",
axes = FALSE
)
axis(
side = 1,
pos = ylim[1],
at = c(0,7),
tick = TRUE,
labels = FALSE
)
axis(
side = 2,
tick = TRUE,
at = yticks,
labels = ylab,
las = 1
)
axis works fine with cateory but you should set the right ticks values and play with pos parameter for offset translation. Here I use xvals the return value of bargraph.CI to set àxis tick marks.
Here a reproducible example:
library(sciplot)
# I am using some sciplot data
dat <- ToothGrowth
### I create along labels
labels <- c('aaaaaaaaaa\naaaaaaaaaaa\nhhhhhhhhhhhhhhh',
'bbbbbbbbbb\nbbbbbbbbbbb\nhhhhhhhhhhhhhh',
'cccccccccc\nccccccccccc\ngdgdgdgdgd')
## I change factor labels
dat$dose <- factor(dat$dose,labels=labels)
ll <- bargraph.CI(x.factor = dose, response = len, data = dat,axisnames=FALSE)
## set at to xvals
axis(side=1,at=ll$xvals,labels=labels,pos=-2,tick=FALSE)

How can I make my vertical labels fit within my plotting window?

I'm creating a histogram in R which displays the frequency of several events in a vector. Each event is represented by an integer in the range [1, 9]. I'm displaying the label for each count vertically below the chart. Here's the code:
hist(vector, axes = FALSE, breaks = chartBreaks)
axis(1, at = tickMarks, labels = eventTypes, las = 2, tick = FALSE)
Unfortunately, the labels are too long, so they are cut off by the bottom of the window. How can I make them visible? Am I even using the right chart?
Look at help(par), in particular fields mar (for the margin) and oma (for outer margin).
It may be as simple as
par(mar=c(5,3,1,1)) # extra large bottom margin
hist(vector, axes = FALSE, breaks = chartBreaks)
axis(1, at = tickMarks, labels = eventTypes, las = 2, tick = FALSE)
This doesn't sound like a job for a histogram - the event is not a continuous variable. A barplot or dotplot may be more suitable.
Some dummy data
set.seed(123)
vec <- sample(1:9, 100, replace = TRUE)
vec <- factor(vec, labels = paste("My long event name", 1:9))
A barplot is produced via the barplot() function - we provide it the counts of each event using the table() function for convenience. Here we need to rotate labels using las = 2 and create some extra space of the labels in the margin
## lots of extra space in the margin for side 1
op <- par(mar = c(10,4,4,2) + 0.1)
barplot(table(vec), las = 2)
par(op) ## reset
A dotplot is produced via function dotchart() and has the added convenience of sorting out the plot margins for us
dotchart(table(vec))
The dotplot has the advantage over the barplot of using much less ink to display the same information and focuses on the differences in counts across groups rather than the magnitudes of the counts.
Note how I've set the data up as a factor. This allows us to store the event labels as the labels for the factor - thus automating the labelling of the axes in the plots. It also is a natural way of storing data like I understand you to have.
Perhaps adding \n into your labels so they will wrap onto 2 lines? It's not optimal, but it may work.
You might want to look at this post from Cross Validated

Resources