Align Grid() to Plot Ticks

Align grid() to plot ticks

You could use abline to draw grids. You can specify where the grids should be with h (for horizontal lines) and v (for vertical lines)

#Plot
plot(1:10,las=1,xaxp = c(0, 10, 10),xlim=c(0,10), ylim=c(0,10))
#Add horizontal grid
abline(h = c(0,2,4,6,8,10), lty = 2, col = "grey")
#Add vertical grid
abline(v = 1:10, lty = 2, col = "grey")

Another workaround is to use axis where tck value is 1. With axis, you can specify where the grids should be with at

#Plot
plot(1:10,las=1,xaxp = c(0, 10, 10),xlim=c(0,10), ylim=c(0,10))

#Add horizontal grid
axis(2, at = c(0,2,4,6,8,10), tck = 1, lty = 2, col = "grey", labels = NA)

#Add vertical grid
axis(1, at = 1:10, tck = 1, lty = 2, col = "grey", labels = NA)

#Add box around plot
box()

Sample Image

Align grid with ticks

Looks like abline is the answer:

mytime <- as.POSIXct("2015-08-20") + seq(0,by=3600,length.out=7*24)
plot(x=mytime,y=rnorm(7*24),xaxt="n")
ticks <- c(mytime[seq(1,by=12,to=length(mytime))],mytime[1]+7*24*3600)
axis(1, ticks, strftime(ticks, "%a %H:%M"))
grid(ny=NULL,nx=NA)
abline(v=ticks[seq(1,length(ticks),2)],lty="dotted",col="lightgray")

Sample Image

Grid line consistent with ticks on axis

From ?grid description of the nx and ny arguments:

When NULL, as per default, the grid aligns with the tick marks on the
corresponding default axis (i.e., tickmarks as computed by axTicks)

plot (x = 1:10, y = rnorm (10, 5, 2)) 
grid (NULL,NULL, lty = 6, col = "cornsilk2")

Getting ticks on same horizontal grid for plots with different scale

One could align the right ticks by setting their ylims to the corresponding ylims of the left:

ymin1, ymax1 = ax1.get_ylim()
ax2.set_ylim(ymin1 / 10000, ymax1 / 10000)

Or set the ylims of both axes to the widest range:

import numpy as np
import matplotlib.pyplot as plt

# Create some mock data
t = np.arange(0.01, 10.0, 0.01)
data1 = np.exp(t)
data2 = np.sin(2 * np.pi * t)

fig, ax1 = plt.subplots()

color = 'tab:red'
ax1.set_xlabel('time (s)')
ax1.set_ylabel('exp', color=color)
ax1.plot(t, data1, color=color)
ax1.tick_params(axis='y', labelcolor=color)

ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis

color = 'tab:blue'
ax2.set_ylabel('sin', color=color) # we already handled the x-label with ax1
ax2.plot(t, data2, color=color)
ax2.tick_params(axis='y', labelcolor=color)

ymin1, ymax1 = ax1.get_ylim()
ymin2, ymax2 = ax2.get_ylim()
ymin1 = min(ymin1, ymin2 * 10000)
ymax1 = max(ymax1, ymax2 * 10000)
ax1.set_ylim(ymin1, ymax1)
ax2.set_ylim(ymin1 / 10000, ymax1 / 10000)

ax1.grid(True, axis='y')
fig.tight_layout() # otherwise the right y-label is slightly clipped
plt.show()

result

How do I align gridlines for two y-axis scales using Matplotlib?

I am not sure if this is the prettiest way to do it, but it does fix it with one line:

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd

np.random.seed(0)
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(pd.Series(np.random.uniform(0, 1, size=10)))
ax2 = ax1.twinx()
ax2.plot(pd.Series(np.random.uniform(10, 20, size=10)), color='r')

# ADD THIS LINE
ax2.set_yticks(np.linspace(ax2.get_yticks()[0], ax2.get_yticks()[-1], len(ax1.get_yticks())))

plt.show()

Placing the grid along date tickmarks

abline can extract the date ticks from your POSIXlt vector (via strptime).

x=strptime(20010101:20010110,format="%Y%m%d")
y=1:10

plot(x,y)
grid(nx=NA, ny=NULL)
abline(v=axis.POSIXct(1, x=pretty(x)),col = "lightgray", lty = "dotted", lwd = par("lwd"))

I would suggest creating your own function which would add both horizontal and vertical grids.

my.grid <-function(){
grid(nx=NA, ny=NULL)
abline(v=axis.POSIXct(1, x=pretty(x)),col = "lightgray", lty = "dotted", lwd =
par("lwd"))
}

plot(x,y)
my.grid()

matplotlib align twinx tick marks

You need to manually set the yticks as it stands these are automatically calculated resulting in a variation. Adding something like this:

ax1.set_yticks(np.linspace(ax1.get_ybound()[0], ax1.get_ybound()[1], 5))
ax2.set_yticks(np.linspace(ax2.get_ybound()[0], ax2.get_ybound()[1], 5))

where we set the ytick locations using an array of 5 points between the bounds of the axis. Since you have a histogram you could just set the lower value to zero in each case, and you may want to have the upper bound somewhat larger, so I would instead have

ax1.set_yticks(np.linspace(0, ax1.get_ybound()[1]+1, 5))
ax2.set_yticks(np.linspace(0, ax2.get_ybound()[1]+1, 5))

Giving a plot (with a change of color and transparency (alpha) for clarity):

Sample Image

D3.js y- axis ticks and grid lines do not align

I created a fiddle.

that while I had to change a few things to account for no angular, but shows the axis gridlines and labels aligned. I moved everything into one g group is is then translated and the individual components are no longer translated.



Related Topics



Leave a reply



Submit