xticklabels disappear when using ax.twin in subplots - python

I'm trying to create a 2 rows subplots using pandas plot, where the upper subplots has secondary y axis, but the creation of the secondary axis makes the xticklabels disappear as shown below.
I used the following code:
fig,axes=plt.subplots(2,1)
ax=axes[0]
pd.Series(range(10)).plot(ax=ax)
ax2=ax.twinx()
(pd.Series(range(10))**2).plot(ax=ax2)
ax=axes[1]
pd.Series(range(10)).plot(ax=ax)
when using the same code but replacing the order of the subplots it works fine:
fig,axes=plt.subplots(2,1)
ax=axes[0]
pd.Series(range(10)).plot(ax=ax)
ax=axes[1]
pd.Series(range(10)).plot(ax=ax)
ax2=ax.twinx()
(pd.Series(range(10))**2).plot(ax=ax2)

For this, I suggest using matplotlib as is, and not through pandas. That should solve your issue.
So it would be something like this:
import matplotlib.pyplot as plt
fig,axes=plt.subplots(2,1)
ax=axes[0]
ax.plot(pd.Series(range(10)))
ax2=ax.twinx()
ax2.plot(pd.Series(range(10))**2)
ax=axes[1]
ax.plot(pd.Series(range(10)))

Related

Why is my MatPlotLib split axes graph not appearing?

I tried to create a graph side by side using matplotlib.
I don't get any errors when I run my code, instead, I just get a blank window from MatPlotLib.
Here's the link I used for my CSV.
https://ca.finance.yahoo.com/quote/%5EGSPTSE/history?p=%5EGSPTSE
Previously, I have also created a graph that overlayed the two lines(which works as intended), but they are not displaying as seperate graphs, which is what I am trying to do with my current code.
I tried this video for information in creating these graphs, but I can't replicate the graph shown in the video even when I copy the code.
https://www.youtube.com/watch?v=-2AMr95nUDw
from matplotlib import pyplot as mpl
import pandas as pd
data_better = pd.read_csv('What.csv')
# print(data_better.head()) #I used this part to find out what the headers were for x values
# print(data_better.columns[::])
mpl.axes([15000, 17000, 20000, 23000])
mpl.title("Open Values")
mpl.plot(data_better["Date"], data_better["Open"])
mpl.ylabel("Money")
mpl.axes([15000, 17000, 20000, 23000])
mpl.title("Close Values")
mpl.plot(data_better["Date"], data_better["Close"])
mpl.ylabel("Money")
mpl.show()
pyplot.axes accepts 4-tuple of floats in normalized (0, 1) units to place the axes. You can look at examples in Make Room For Ylabel Using Axesgrid to learn using it.
If you want to plot two plots in one figure, you need use different axes
from matplotlib import pyplot as plt
import pandas as pd
data_better = pd.read_csv('What.csv')
figure, (axes1, axes2) = plt.subplots(nrows=1, ncols=2)
axes1.set_title("Open Values")
axes1.plot(data_better["Date"], data_better["Open"])
axes1.set_ylabel("Money")
axes2.set_title("Close Values")
axes2.plot(data_better["Date"], data_better["Close"])
axes2.set_ylabel("Money")
plt.show()

How to reposition title in seaborn.FacetGrid if tight_layout is applied?

I have a simple seaborn FacetGrid() with barplots inside.
I applied tight_layout() to my final plot, as xticks had to be properly positioned on the plot after rotation.
As result, when I want to add the title to the plot it is positioned in the wrong place, basically over the existing axes.
So, my question is how should the title be manipulated in order to be properly positioned in case tight_layout() is applied?
I reproduced the issue with the standard tips dataset:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
tips = sns.load_dataset("tips")
days_dict = {day:day+', a long name' for day in tips['day'].unique()}
tips['day_long'] = tips['day'].map(lambda x: days_dict[x])
grid = sns.FacetGrid(tips,col='size',col_wrap=3,height=4,sharex=False)
grid.map(sns.barplot, 'day_long', 'total_bill').set_titles('{col_name}')
grid.fig.set_size_inches(10,10)
grid.fig.suptitle('Title (it should be placed higher)',fontsize=16)
for ax in grid.axes.flat:
for label in ax.get_xticklabels():
label.set_rotation(90)
plt.tight_layout()
plt.show()
Add (adjust the value to your taste)
grid.fig.subplots_adjust(top=0.90)
after tight_laout() to make some room at the top of the plot for the suptitle()

Histogram of a dataframe

I have a data frame as follow:
and I am trying to plot a histogram from it such that the letters {A,B,C,D} are in the x axis and y axis shows the numbers. I have tried the following:
df.plot(kind='hist')
for which I get the address instead of the plot, i.e:
<matplotlib.axes._subplots.AxesSubplot at 0x11217d5f8>
I was wondering how can I show the plot?
IIUC, I think you need to transpose the dataframe to get index ['A','B','C','D']as x-axis and then plot. Also use plt.show() to display the histogram. The latest version of pandas will display directly the plot with axes object displaying. But, for the older versions need to explicitly write the plt.show() code to display.
import matplotlib.pyplot as plt
df.T.plot(kind='hist')
plt.show()

Order in legend plots python

I need to plot multiple sets of data on the same plot, and I use matplotlib.
For some of plots I use plt.plot() and for the others I use plt.errorbar(). But when I make a legend the ones created with plt.plot() appears first, no matter in which order I put them in the file (and zorder seems to have no effect on the position in the legend).
How can I give the order that I want in the legend, regardless of the way I plot the data?
You can adjust the order manually, by getting the legend handles and labels using ax.get_legend_handles_labels, and then reordering the resulting lists, and feeding them to ax.legend. Like so:
import matplotlib.pyplot as plt
import numpy as np
fig,ax = plt.subplots(1)
ax.plot(np.arange(5),np.arange(5),'bo-',label='plot1')
ax.errorbar(np.arange(5),np.arange(1,6),yerr=1,marker='s',color='g',label='errorbar')
ax.plot(np.arange(5),np.arange(2,7),'ro-',label='plot2')
handles,labels = ax.get_legend_handles_labels()
handles = [handles[0], handles[2], handles[1]]
labels = [labels[0], labels[2], labels[1]]
ax.legend(handles,labels,loc=2)
plt.show()

Remove axes in matplotlib subplots?

I've got a pandas dataframe with 4 columns and a date range as the index. After showing the trend lines on four subplots using this code, I realized I don't want the y axis ticks or labels, but I can't find any advice on removing them from the subplots; everything I try only works on the bottom plot.
plot4 = CZBCdf2.plot(subplots=True,figsize=(10,4),sharex=True)
The typical way of removing axis in matplotlib is:
import matplotlib.pyplot as plt
plt.axis('off')
This, however, is a general instruction in matplotlib. To set the axis to invisible you can do (using a subplot):
ax.xaxis.set_visible(False) # same for y axis.
You seem to be calling the plot from other source. If this instructions don't do the stuff you need provide more of your code to see what might be the procedure to achieve that.
A complete solution to remove anything around the plot
figure, axis = plt.subplots(1, figsize=[10,3])
axis.plot(...)
axis.xaxis.set_visible(False)
axis.yaxis.set_visible(False)
for spine in ['top', 'right', 'left', 'bottom']:
axis.spines[spine].set_visible(False)
figure.savefig('demo.png', bbox_inches='tight', transparent="True", pad_inches=0, )
Set yticks=[]
So, in your example:
plot4 = CZBCdf2.plot(subplots=True,figsize=(10,4),sharex=True, yticks=[])

Categories

Resources