I have the following code:
fig = plt.figure()
ax1 = plt.subplot(211)
ax2 = plt.subplot(212, sharex = ax1)
ax2 = ax1.twinx()
num = list111.lt(-90).sum(1)
plt.yticks(fontsize = 25)
ax = num.plot(figsize=(45,25), ax=ax2, color = 'Red')
df2.plot(y = 'Close', figsize=(45,25), ax=ax1, color = 'Green')
ax1.grid()
ax.margins(x=0)
I am trying to plot ax1 and ax2 in the same graph. What i am getting is a ghost plot:
How can i get rid of the second ghost plot and move the x axis with label to the top plot?
The statement
ax2 = plt.subplot(212, sharex = ax1)
generates a subplot located beneath the ax1 subplot. But it is in contradiction with the statement
ax2 = ax1.twinx()
which points towards a secondary y-axis on the ax1 axes.
If you want all the data to be plotted only on a single axes, you can delete the first statement and use the .twinx() method:
ax1 = plt.axes()
ax2 = ax1.twinx()
# remaining code
otherwise, use both axes separately with
ax1 = plt.subplot(211)
ax2 = plt.subplot(212, sharex = ax1)
# remaining code
Related
I have problems with the rotation of my X-axis, I have tried to do the rotation the output plot without errors, but I do not have the results.
# Import Data
#df = pd.read_csv("https://github.com/selva86/datasets/raw/master/economics.csv")
x = total_test["Dia"].values[:]; y1 = total_test["Confirmados"].values[:]; y2 = total_test["Fallecidos"].values[:]
# Plot Line1 (Left Y Axis)
fig, ax1 = plt.subplots(1,1,figsize=(10,8), dpi= 200)
ax1.plot(x, y1,'g^', color='tab:red')
# Plot Line2 (Right Y Axis)
ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis
ax2.plot(x, y2,'bs', color='tab:blue')
# Just Decorations!! -------------------
# ax1 (left y axis)
ax1.set_xlabel('Dias', fontsize=10)
ax1.set_ylabel('Personas Confirmadas', color='tab:red', fontsize=20)
ax1.tick_params(axis='y', rotation=0, labelcolor='tab:red' )
# ax2 (right Y axis)
ax2.set_ylabel("Personas Fallecidas", color='tab:blue', fontsize=20)
ax2.tick_params(axis='y', rotation=0, labelcolor='tab:blue')
ax2.set_title("Personas Confirmadas y Fallecidas por Covid-19 Peru", fontsize=15)
#ax2.set_xticks(x)
ax2.set_xticklabels(x[::],fontsize=10,rotation=90)
plt.show()
Any commands for the xaxis need to occur before ax2.
Verify date is in a datetime format and set as the index.
import pandas as pd
import matplotlib.pyplot as plt
# read data
df = pd.read_csv("https://github.com/selva86/datasets/raw/master/economics.csv")
# verify the date column is a datetime format and set as index
df['date'] = pd.to_datetime(df['date'])
df.set_index('date', inplace=True)
#plot
# create figure
fig, ax1 = plt.subplots(1, 1, figsize=(10,8))
# 1st plot
ax1.plot(df['pop'], color='tab:red')
# set xticks rotation before creating ax2
plt.xticks(rotation=90)
# 2nd plot (Right Y Axis)
ax2 = ax1.twinx() # create the 'twin' axis on the right
ax2.plot(df['unemploy'], color='tab:blue')
plt.show()
Plot directly with pandas.DataFrame.plot
# load data
df = pd.read_csv("https://github.com/selva86/datasets/raw/master/economics.csv", parse_dates=True, index_col=[0])
# plot and rotate the tick labels with rot= in the first plot call
ax = df.plot(y='pop', color='tab:red', figsize=(10,8), rot=90)
ax2 = ax.twinx()
df.plot(y='unemploy', color='tab:blue', ax=ax2)
ax2.legend(loc='upper right')
I have this code for a graph, and I do not want the values & ticks on the top and right axes.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
#Set axis labels
ax.set_xlabel('NEGATIVE')
ax.set_ylabel('HAPPY')
ax2 = ax.secondary_xaxis('top')
ax2.set_xlabel('POSITIVE')
ax2 = ax.secondary_yaxis('right')
ax2.set_ylabel('SAD')
#Remove ticks/values
ax.set_yticklabels([])
ax.set_xticklabels([])
ax.set_yticks([])
ax.set_xticks([])
ax2.set_yticklabels([])
ax2.set_xticklabels([])
ax2.set_yticks([])
ax2.set_xticks([])
#Show graph
plt.show()
it's showing it like this: image of graph
Use tick_params to manipulate the axis ticks and labels:
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
#Set axis labels
ax1.set_xlabel('NEGATIVE')
ax1.set_ylabel('HAPPY')
ax2 = ax1.secondary_xaxis('top')
ax2.set_xlabel('POSITIVE')
ax3 = ax1.secondary_yaxis('right')
ax3.set_ylabel('SAD')
#Remove ticks/values
for ax in (ax1, ax2, ax3):
ax.tick_params(left=False, labelleft=False, top=False, labeltop=False,
right=False, labelright=False, bottom=False, labelbottom=False)
#Show graph
plt.show()
A comment asked for how to only turn top and left ticks and labels off. This would be
for ax in (ax1, ax2, ax3):
ax.tick_params(top=False, labeltop=False, right=False, labelright=False)
Interesting why SecondaryAxis doesn't accept tick params, however let's use twinx and twiny:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
#Set axis labels
ax.set_xlabel('NEGATIVE')
ax.set_ylabel('HAPPY')
ax2x = ax.twiny()
ax2.set_yticks([])
ax2x.set_xlabel('POSITIVE')
ax2y = ax.twinx()
ax2y.set_ylabel('SAD')
ax2x.set_xticks([])
ax2y.set_yticks([])
#Show graph
plt.show()
Output:
I have a large census dataset I am working with and am taking different data from it and representing it as a singular .png in the end. I have created the graphs individually, but when I try to add them to the subplots they get distorted or axis get messed up.
Current code:
fig = plt.figure()
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3)
ax4 = fig.add_subplot(2, 2, 4)
ax1.pie(df.data.valuecounts(normalize=True),labels=None,startangle-240)
ax1.legend(['a','b','c','d','e'])
ax1.axis('equal')
data2=df[['A']].dropna().values
kde=df.A.plot.kde()
binss = np.logspace(0.01,7.0)
ax2=plt.hist(hincp, normed=True, bins=binss)
ax2=plt.xscale('log')
ax3 = df.replace(np.nan,0)
ax3 = (df.groupby(['G'])['R'].sum()/1000)
ax3.plot.bar(width=0.9, color='red',title='Gs').set_ylabel('Rs')
ax3.set_ylabel('Rs')
ax3.set_xlabel('# G')
t = df[['p','o','s','y']]
ax4=plt.scatter(t.o,t.p,s=t.s,c=t.y, marker = 'o', alpha = 0.2)
plt.ylim(0, 10000)
plt.xlim(0,1200000)
cbar=plt.colorbar()
plt.title("this vs that", loc = 'center')
plt.xlabel('this')
plt.ylabel('that')
All four types of graphs should be displayed and not overlap.
You create Axes for each subplot but then you don't use them.
ax1.pie(...) looks correct but later you don't use ax2,ax3,ax4.
If you are going to to use the DataFrame plotting methods, just call plt.subplot before each new plot. Like this.
df = pd.DataFrame(np.random.random((6,3)))
plt.subplot(3,1,1)
df.loc[:,0].plot()
plt.subplot(3,1,2)
df.loc[:,1].plot()
plt.subplot(3,1,3)
df.loc[:,2].plot()
plt.show()
plt.close()
Or use the Axes that you create.
df = pd.DataFrame(np.random.random((6,3)))
fig = plt.figure()
ax1 = fig.add_subplot(3,1,1)
ax2 = fig.add_subplot(3,1,2)
ax3 = fig.add_subplot(3,1,3)
ax1.plot(df.loc[:,0])
ax2.plot(df.loc[:,1])
ax3.plot(df.loc[:,2])
plt.show()
plt.close()
I have tried the following:
d = [1,2,3,4,5,6,7,8,9]
f = [0,1,0,0,1,0,1,1,0]
fig = plt.figure()
fig.set_size_inches(30,10)
ax1 = fig.add_subplot(211)
line1 = ax1.plot(d,marker='.',color='b',label="1 row")
ax2 = fig.add_subplot(212)
line1 = ax2.plot(f,marker='.',color='b',label="1 row")
ax1.grid()
ax2.grid()
plt.show()
I got the following output :
But I was expecting the following output:
How I can get the grids across the two plots?
There is no built-in option to create inter-subplot grids. In this case I'd say an easy option is to create a third axes in the background with the same grid in x direction, such that the gridline can be seen in between the two subplots.
import matplotlib.pyplot as plt
d = [1,2,3,4,5,6,7,8,9]
f = [0,1,0,0,1,0,1,1,0]
fig, (ax1,ax2) = plt.subplots(nrows=2, sharex=True)
ax3 = fig.add_subplot(111, zorder=-1)
for _, spine in ax3.spines.items():
spine.set_visible(False)
ax3.tick_params(labelleft=False, labelbottom=False, left=False, right=False )
ax3.get_shared_x_axes().join(ax3,ax1)
ax3.grid(axis="x")
line1 = ax1.plot(d, marker='.', color='b', label="1 row")
line1 = ax2.plot(f, marker='.', color='b', label="1 row")
ax1.grid()
ax2.grid()
plt.show()
Here is my solution:
import matplotlib.pyplot as plt
x1 = [1,2,3,4,5,6,7,8,9]
x2= [0,1,0,0,1,0,1,1,0]
x3= range(-10,0)
# frameon=False removes frames
# fig, (ax1,ax2, ax3) = plt.subplots(nrows=3, sharex=True, subplot_kw=dict(frameon=False))
fig, (ax1,ax2, ax3) = plt.subplots(nrows=3, sharex=True)
# remove vertical gap between subplots
plt.subplots_adjust(hspace=.0)
ax1.grid()
ax2.grid()
ax3.grid()
ax1.plot(x1)
ax2.plot(x2)
ax3.plot(x3)
Without frames subplot_kw=dict(frameon=False):
An option is to create a single plot then just offset the data. So one set plots above the other.
I'm trying to create a subplot using matplotlib using gridspec.
I was wondering why matplotlib isn't putting correct x limits on the plot.
x values are a range from 0 to 40, but the plot only shows 1 datapoint, as the plottet x axis only reaches from -0.06 to 0.06.
Do I have to set the xlim manually when using subplot + gridspec?
x = range(0, len(stuff["training"]))
y = stuff["training"]
fig = plt.figure()
gs = gridspec.GridSpec(3, 1)
ax1 = fig.add_subplot(gs[0:2])
ax2 = fig.add_subplot(gs[-1], sharex=ax1)
plt.setp(ax2.get_xticklabels(), visible=False)
plt.setp([ax1, ax2], title='Test')
ax1.scatter(x, stuff["training"])
ax2.plot(x, stuff["lr"])
fig.suptitle('An overall title', size=20)
gs.tight_layout(fig, rect=[0, 0, 1, 0.97])
EDIT: I think I found the problem
This is not working:
ax1 = fig.add_subplot(gs[0:2])
ax2 = fig.add_subplot(gs[-1], sharex=ax1)
ax1.scatter(x,y)
This is working:
ax1 = fig.add_subplot(gs[0:2])
ax1.scatter(x,y)
ax2 = fig.add_subplot(gs[-1], sharex=ax1)