I have the following code:
from pandas_datareader import data as web
import matplotlib.pyplot as plt
fig, (ax1, ax2) = plt.subplots(2, 1)
df = web.DataReader('F', 'yahoo')
df2 = web.DataReader('Fb', 'yahoo')
ax = df.plot(figsize=(35,15), ax=ax1)
df2.plot(y = 'Close', figsize=(35,15), ax=ax2)
plt.show()
This produces the chart which looks like this:
How can i change the minor ticks in pandas plot so it produces the x axis which looks like this:
Check this code:
from pandas_datareader import data as web
import matplotlib.pyplot as plt
import matplotlib.dates as md
fig, (ax1, ax2) = plt.subplots(2, 1)
df = web.DataReader('F', 'yahoo')
df2 = web.DataReader('Fb', 'yahoo')
ax = df.plot(figsize=(35,15), ax=ax1)
df2.plot(y = 'Close', figsize=(35,15), ax=ax2)
for ax in (ax1, ax2):
ax.xaxis.set_major_locator(md.MonthLocator(bymonth = range(1, 13, 6)))
ax.xaxis.set_major_formatter(md.DateFormatter('%b\n%Y'))
ax.xaxis.set_minor_locator(md.MonthLocator())
plt.setp(ax.xaxis.get_majorticklabels(), rotation = 0 )
plt.show()
You can manage the xticks with the ax.xaxis methods. The above code produce this plot:
Related
I have the following code:
import pandas.util.testing as testing
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib as mpl
df = testing.makeTimeDataFrame(freq='MS')
with mpl.rc_context(rc={'font.family': 'serif', 'font.weight': 'bold', 'font.size': 12}):
fig = plt.figure(figsize= (12, 6))
fig.add_subplot(2, 2, (1,2))
ax2 = ax.twinx()
df['A'].plot(ax=ax, color = 'g')
df['B'].plot(ax=ax2, color ='g')
fig.add_subplot(223)
df['C'].plot(color='r')
fig.add_subplot(224)
df['D'].plot()
fig.tight_layout()
plt.show()
Which produces the following plot.
I am trying to plot df['A'] and df['B'] on the same top plot. Could you please advise what I have overlooked?
one little detail is missing. before calling twinx you need to assign ax to the first subplot. Then it'll work.
ax = fig.add_subplot(2, 2, (1,2))
I have the following code that generates a Heatmap in Pandas:
def create_cohort(cohort_size,retention_matrix,titulo):
print(f"{titulo}\n")
with sns.axes_style("white"):
fig, ax = plt.subplots(1, 2, figsize=(12, 8), sharey=True, gridspec_kw={'width_ratios': [1, 11]})
# retention matrix
sns.heatmap(retention_matrix,
mask=retention_matrix.isnull(),
annot=True,
fmt='.0%',
cmap='Purples',
ax=ax[1])
ax[1].set_title(f'Cohort: {titulo}', fontsize=16)
ax[1].set(xlabel='Meses',
ylabel='')
# cohort size
cohort_size_df = pd.DataFrame(cohort_size).rename(columns={0: 'Tamanho da cohort'})
white_cmap = mcolors.ListedColormap(['white'])
sns.heatmap(cohort_size_df,
annot=True,
cbar=False,
fmt='.0f',
cmap=white_cmap,
ax=ax[0])
fig.tight_layout()
return
This is a example of graph:
I would like to change the format of the most left table to add '$' before the number. I know I have to change the fmt='.0f', but I do not know how. I also could not find documentation on the values I can pass in the fmt parameter. Can someone also explain to me how this works? What values can I use?
Instead of just setting annot=True, a list of strings, with the same shape as the dataframe can be provided:
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from matplotlib.ticker import PercentFormatter
import seaborn as sns
import pandas as pd
N = 12
cohort_size = pd.DataFrame({0: np.random.randint(20000, 50000, N)}, index=[f'2021:{i:02d}' for i in range(1, 13)])
retention_matrix = np.random.rand(N, N)
retention_matrix[:, 0] = 1
retention_matrix = np.where(np.tril(retention_matrix)[::-1], retention_matrix, np.NaN)
with sns.axes_style("white"):
fig, ax = plt.subplots(1, 2, figsize=(12, 8), sharey=True, gridspec_kw={'width_ratios': [1, 11]})
sns.heatmap(retention_matrix,
annot=True,
fmt='.0%',
cmap='Purples',
cbar_kws={'format': PercentFormatter(1)},
ax=ax[1])
ax[1].set(xlabel='Meses', ylabel='')
cohort_size_df = pd.DataFrame(cohort_size).rename(columns={0: 'Tamanho da cohort'})
labels = [[f'$ {s:,d}'] for s in cohort_size_df.iloc[:, 0]]
sns.heatmap(cohort_size_df,
annot=labels,
cbar=False,
fmt='',
cmap=ListedColormap(['white']),
ax=ax[0])
ax[0].tick_params(axis='y', labelrotation=0)
fig.tight_layout()
plt.show()
This is a follow up for a question which i asked here:
The code is as follows:
from pandas_datareader import data as web
import matplotlib.pyplot as plt
import matplotlib.dates as md
fig, (ax1, ax2) = plt.subplots(2, 1)
df = web.DataReader('F', 'yahoo')
df2 = web.DataReader('Fb', 'yahoo')
ax = df.plot(figsize=(35,15), ax=ax1)
df2.plot(y = 'Close', figsize=(35,15), ax=ax2)
plt.xticks(fontsize = 25)
for ax in (ax1, ax2):
ax.xaxis.set_major_locator(md.MonthLocator(bymonth = range(1, 13, 6)))
ax.xaxis.set_major_formatter(md.DateFormatter('%b\n%Y'))
ax.xaxis.set_minor_locator(md.MonthLocator())
plt.setp(ax.xaxis.get_majorticklabels(), rotation = 0 )
plt.show()
This produces this plot:
How can i increase the size of both the xticks in the two subplots as you can see the size was increased for the bottom one only.
[1]: https://stackoverflow.com/questions/62358966/adding-minor-ticks-to-pandas-plot
You can use the tick_params function on the ax instance to control the size of the tick-labels on the x-axis. If you want to control the size of both x and y axis, use axis='both'. You can additionally specify which='major' or which='minor' or which='both' depending on if you want to change major, minor or both tick labels.
for ax in (ax1, ax2):
# Rest of the code
ax.tick_params(axis='x', which='both', labelsize=25)
I'm trying to print a grid of seaborn plots by using a list of column names. It is plotting everything on the last plot.
fig, ax = plt.subplots(2,2, figsize=(10,10), sharex=True)
for aa in listA:
for j in range(2):
for i in range(2):
ax[i][j] = sns.lineplot(x='time', y=aa, data=new_df, color='r')
Output plot
One way is to flatten the ax and iterate through them. You can call plt from matplotlib directly:
import pandas as pd
import matplotlib. pyplot as plt
dates = pd.date_range(start='1/1/2018', periods=10, freq='1D')
listA = [np.random.normal(0,1,10) for i in range(4)]
new_df = pd.DataFrame({'time':dates })
fig, ax = plt.subplots(2,2, figsize=(10,10), sharex=True)
ax = ax.flatten()
for i,aa in enumerate(listA):
ax[i].plot(new_df['time'], aa, color='r')
ax[i].set_xticklabels(new_df['time'], rotation = 45, ha="right",fontsize=7)
If you really wanna use seaborn, it goes like:
fig, ax = plt.subplots(2,2, figsize=(10,10), sharex=True)
ax = ax.flatten()
for i,aa in enumerate(listA):
sns.lineplot(x=new_df['time'], y=aa, color='r',ax=ax[i])
ax[i].set_xticklabels(new_df['time'], rotation = 45, ha="right",fontsize=7)
Try replacing the following line of code:
ax[i][j] = sns.lineplot(x='time', y=aa, data=new_df, color='r')
with the following:
ax[i,j] = sns.lineplot(x='time', y=aa, data=new_df, color='r')
fig, ax = plt.subplots(2,2, figsize=(15,5))
a = 0
for j in range(2):
for i in range(2):
sns.lineplot(x='time', y=listA[a], data=new_df[new_df['transportation_type']=='walking'], ax=ax[i,j])
a+=1
I'm trying to create a simple 1 by 3 subplot of the maps I have. They only have 2 dimensions (longitude and latitude) after time averaging. The final map plots perfectly, but the first two subplots are just blank.
Thanks in advance for any advice!
import numpy as np
import xarray as xa
import cmocean.cm as cm
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
lgm = xa.open_dataset('lgm.nc', decode_times=False)
pre = xa.open_dataset('pre-i.nc', decode_times=False)
pd = xa.open_dataset('present.nc', decode_times=False)
def pco2_diff():
lgm_pco2 = lgm.O_pco2sur
pre_pco2 = pre.O_pco2sur
pd_pco2 = pd.O_pco2sur
#-------------------------Time averaged data-------------------------------
lgm_pco2_mean = lgm_pco2.mean("time")
pre_pco2_mean = pre_pco2.mean("time")
pd_pco2_mean = pd_pco2.mean("time")
#-----------------Get the ocean-atmosphere fluxes--------------------------
lgm_pco2_diff = lgm_pco2_mean - 189.65
pre_pco2_diff = pre_pco2_mean - 277.44
pd_pco2_diff = pd_pco2_mean - 368.89
#---------------------Basic plots, 1 at a time-----------------------------
lgm_pco2_diff.plot()
pre_pco2_diff.plot()
pd_pco2_diff.plot()
#-----------------------------Subplots-------------------------------------
f, (ax1, ax2, ax3) = plt.subplots(1, 3, sharey=True, sharex=False)
#1 row, 3 columns, sharing the y-axis, not sharing the x-axis
ax1 = lgm_pco2_diff.plot(vmin=-300, vmax=300, add_colorbar=False)
ax2 = pre_pco2_diff.plot(vmin=-300, vmax=300, add_colorbar=False)
ax3 = pd_pco2_diff.plot(vmin=-300, vmax=300,cmap=cm.thermal)
Maybe try the following:
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, sharey=True, sharex=False)
ax1.plot(lgm_pco2_diff, vmin=-300, vmax=300, add_colorbar=False)
ax2.plot(pre_pco2_diff, vmin=-300, vmax=300, add_colorbar=False)
ax3.plot(pd_pco2_diff, vmin=-300, vmax=300, cmap=cm.thermal)