Issue
I have a dataframe
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
data = {
'id': [1, 2, 3, 4, 5,6,7,8,9,10],
'LeftError': [0.1, 0.2, 0.15, 0.3, 0.25,-0.1, -0.2, -0.15, -0.3, -0.25],
'RightError': [0.2, 0.3, 0.25, 0.4, 0.35,-0.2, -0.3, -0.25, -0.4, -0.35],
'NCL': [1, 2, 1, 3, 2,-1, -2, -1, -3, -2],
'NCR': [2, 3, 2, 4, 3,-2, -3, -2, -4, -3],
}
df = pd.DataFrame(data)
I want to plot it
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
# Plot for Left side
axes[0].scatter(df['NCL'], df['LeftError'], color='blue')
axes[0].set_xlabel('NCL')
axes[0].set_ylabel('Left Error')
# Plot for Right side
axes[1].scatter(df['NCR'], df['RightError'], color='green')
axes[1].set_xlabel('NCR')
axes[1].set_ylabel('Right Error')
plt.show()
You can see that there is a good thing and a bad thing here. The good thing is that the Y axis goes a bit more and less than the range of values (it does not cross the points) . The bad thing is that they show different values. So to correct the bad thing I do
axes[0].set_ylim((min(df['LeftError'].min(), df['RightError'].min())), (max(df['LeftError'].max(), df['RightError'].max())))
axes[1].set_ylim((min(df['LeftError'].min(), df['RightError'].min())), (max(df['LeftError'].max(), df['RightError'].max())))
and now I get
So the bad thing was corrected, but the good thing became bad. See that the first and last green dot got crossed by the axis
How can I make the axis have some pad as originally but keeping the same values for both?
Solution
Instead of using the data, you can use the already-padded xlim
s and ylim
s of the plots. You just need to take the minimum and maximum of all the axes' limits.
import numpy as np
import matplotlib.pyplot as plt
plt.close("all")
x1 = np.linspace(-4, 4, 10)
x2 = np.linspace(-3, 3, 10)
y1 = 2*x1
y2 = 3*x2
fig, axes = plt.subplots(1, 2)
axes[0].scatter(x1, y1)
axes[1].scatter(x2, y2)
xlim = (min([ax.get_xlim()[0] for ax in axes]),
max([ax.get_xlim()[1] for ax in axes]))
ylim = (min([ax.get_ylim()[0] for ax in axes]),
max([ax.get_ylim()[1] for ax in axes]))
plt.setp(axes, xlim=xlim, ylim=ylim)
Answered By - jared
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.