Consider this code:
fig, ax = plt.subplots(figsize=(8,5))
sns.heatmap(np.ones((4,4)), ax=ax, cbar=None, cmap="Blues", linewidths=1, linecolor='black')
fig, ax = plt.subplots(figsize=(8,5))
sns.heatmap(np.ones((4,4)), ax=ax, cmap="Blues", linewidths=1, linecolor='black')
It outputs:
Why does adding the argument cbar=None change the result of the outcome?
It is the default behavior by cbar, some kind of bug.
Turn off cbar:
fig, ax = plt.subplots(figsize=(8,5))
sns.heatmap(np.ones((4, 4)), ax=ax, cmap='Blues', linewidths=1, linecolor='black', cbar=False, vmin=0, vmax=2)
Turn on cbar:
fig, ax = plt.subplots(figsize=(8,5))
sns.heatmap(np.ones((4,4)), ax=ax, cmap='Blues', linewidths=1, linecolor='black', cbar=True, vmin=0, vmax=2)
As showed by #Alpha, cbar value should be boolean as it can be seen in the documentation
cbar : boolean, optional
Whether to draw a colorbar.
For both figures to have the same size, you can use:
fig, ax = plt.subplots(figsize=(8,5))
sns.heatmap(np.ones((4,4)), ax=ax, linewidths=1, linecolor='black', cmap="Blues",)
cbar = ax.collections[0].colorbar
cbar.remove()
plt.show()
and ...
fig, ax = plt.subplots(figsize=(8,5))
sns.heatmap(np.ones((4,4)), ax=ax, linewidths=1, linecolor='black', cmap="Blues",)
cbar = ax.collections[0].colorbar
#cbar.remove()
plt.show()
Related
I use this code that drow
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data = pd.DataFrame({"Type of defect":["A","B","C","D","E","F","G","Other"], "Count":[17,202,387,25,825,12,3,45]})
data=data.set_index("Type of defect")
data = pd.concat([data[data.index!='Other'].sort_values(by='Count',ascending = False), data[data.index=='Прочее']])
data['Accumulated frequency'] = 100 *data['Count'].cumsum() / data['Count'].sum()
data['Limit']=80
data['Vital few']=np.where((data['Limit'] <= data['Accumulated frequency']) & (data['Limit'].shift(1) <= data['Accumulated frequency'].shift(1)), 0, 100)
fig, axes = plt.subplots()
ax1 = data.plot(use_index=True, y='Count', kind='bar', ax=axes)
ax2 = data.plot(use_index=True, y='Accumulated frequency', marker='D', color="C1", kind='line', ax=axes, secondary_y=True)
ax2.set_ylim([0,110])
ax3 = data.plot(use_index=True, y='Limit', color="gray", kind='line', linestyle='dashed', ax=axes, secondary_y=True)
ax4 = data.plot(use_index=True, y='Vital few', color="yellow", kind='area', ax=axes, secondary_y=True, alpha=0.1)
I get the following picture
However, I need to get this chart
The main problem is how to display "vital few" (Yellow area). There are also problems with the location of the legend and row/column labels. Please help me with this.
Area graphs cannot draw rectangles, so you need to use matplotlib's axvspan(). axvspan() is not reflected in the legend, so you need to add it, and use Patch to set the rectangle and label.
from matplotlib.patches import Patch
fig, axes = plt.subplots()
ax1 = data.plot(use_index=True, y='Count', kind='bar', ax=axes)
ax2 = data.plot(use_index=True, y='Accumulated frequency', marker='D', color="C1", kind='line', ax=axes, secondary_y=True)
ax2.set_ylim([0,110])
ax3 = data.plot(use_index=True, y='Limit', color="gray", kind='line', linestyle='dashed', ax=axes, secondary_y=True)
#ax4 = data.plot(use_index=True, y='Vital few', color="yellow", kind='area', ax=axes, secondary_y=True, alpha=0.1)
axes.axvspan(-0.5,1.25, ymax=0.95,facecolor='yellow', alpha=0.1)
handler1, label1 = ax1.get_legend_handles_labels()
#handler2, label2 = ax2.get_legend_handles_labels()
handler3, label3 = ax3.get_legend_handles_labels()
#print(label1, label2, label3)
add_legend = [Patch(facecolor='yellow', edgecolor='yellow', alpha=0.1, label='Vital few(right)')]
axes.legend(handles=handler1+handler3+add_legend)
plt.show()
EDIT:
If it is strictly linked to the y-axis value, it can be handled by a bar chart as an alternative method. By increasing the default width, the bars will be connected.
ax4 = data.plot(use_index=True, y='Vital few',color='yellow', kind='bar', width=1.0,ax=axes, secondary_y=True, alpha=0.1)
I can write 'A circumflex' as a label on a graph in Python:
df = pd.DataFrame({'x':(0,3,4,0),'y':(3,0,4,3)})
fig, ax = plt.subplots(1,1)
df.plot(x='x', y='y', ax=ax, label='A\u0302', linewidth=5, color='k', linestyle='-')
for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +
ax.get_xticklabels() + ax.get_yticklabels()):
item.set_fontsize(22)
legend = ax.legend(loc=0, ncol=1, bbox_to_anchor=(0.9, -.3, .6, 1),
fancybox=True, shadow=False,
framealpha=1, fontsize=22)
plt.setp(legend.get_title(),fontsize=22)
This gives:
How can I get the circumflex larger please?
Thanks to Mr. T & tmdavison, either $^{A}$ or $\hat{A}$ work for some reason:
df = pd.DataFrame({'x':(0,3,4,0),'y':(3,0,4,3)})
fig, ax = plt.subplots(1,1)
df.plot(x='x', y='y', ax=ax, label='$A\u0302$', linewidth=5, color='k', linestyle='-')
df.plot(x='x', y='y', ax=ax, label='$\^{A}$', linewidth=5, color='k', linestyle='-')
df.plot(x='x', y='y', ax=ax, label='$\hat{A}$', linewidth=5, color='k', linestyle='-')
for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +
ax.get_xticklabels() + ax.get_yticklabels()):
item.set_fontsize(22)
legend = ax.legend(loc=0, ncol=1, bbox_to_anchor=(0.9, -.3, .6, 1),
fancybox=True, shadow=False,
framealpha=1, fontsize=22)
plt.setp(legend.get_title(),fontsize=22)
I have the following code:
f, ax = plt.subplots(1,2, figsize=(20,20))
divider = make_axes_locatable(ax[0])
cax = divider.append_axes("right", size="5%", pad=0.1)
#level_geo.boundary.plot(ax=ax[0], color='black')
level_geo.plot(ax=ax[0], cmap='viridis', column='dem_2001', legend=True, cax=cax)
divider = make_axes_locatable(ax[1])
cax = divider.append_axes("right", size="5%", pad=0.1)
#level_geo.boundary.plot(ax=ax[1], color='black')
level_geo.plot(ax=ax[1], cmap='viridis', column='dem_2030', legend=True, cax=cax)
plt.show()
I am wondering how I share the colour bars so that there is just one bar with a scale relevant to both plots?
If you want just a linear color map, you can just pass vmin and vmax to both plots.
f, ax = plt.subplots(1,2, figsize=(20,20))
divider = make_axes_locatable(ax[0])
cax = divider.append_axes("right", size="5%", pad=0.1)
#level_geo.boundary.plot(ax=ax[0], color='black')
level_geo.plot(ax=ax[0], cmap='viridis', column='dem_2001', legend=True, cax=cax, vmin=0, vmax=1)
divider = make_axes_locatable(ax[1])
cax = divider.append_axes("right", size="5%", pad=0.1)
#level_geo.boundary.plot(ax=ax[1], color='black')
level_geo.plot(ax=ax[1], cmap='viridis', column='dem_2030', legend=True, cax=cax, vmin=0, vmax=1)
plt.show()
Or, better, use min and max retrieved from the data (e.g. level_geo['dem_2030'].min())
ax = df_seeds_train[df_seeds_train['cluster']==0].plot(kind='scatter', x='asymmetry', y='perimeter', s=50, c='green', sharex=False)
df_seeds_train[df_seeds_train['cluster']==1].plot(kind='scatter',x='asymmetry',y='perimeter',s=50, c='orange', sharex=False, ax = ax)
df_seeds_train[df_seeds_train['cluster']==2].plot(kind='scatter',x='asymmetry',y='perimeter',s=50, c='purple', sharex=False, ax = ax)
centers.plot(kind = 'scatter', x='asymmetry', y='perimeter', c='red', s=50, marker='x', sharex=False, ax=ax)
I need to get red markers in the center of my clusters but I keep getting KeyErrors for 'asymmetry' and 'perimeteter'. Does anybody know how to fix this. I added an image of the outcome I get now.Outcome
Thanks in advance!
df_seeds_train
I have the output of a group-by representing a sum of dates per week.
Date
2008-10-28 20.0
2008-11-04 25.0
2008-11-11 20.0
2008-11-18 40.0
2008-11-25 35.0
2008-12-02 35.0
2008-12-09 NaN
2008-12-16 NaN
2008-12-23 NaN
2008-12-30 NaN
Freq: W-TUE, Name: Count, dtype: float64
I'm trying to plot these using plot_date
fig, ax = plt.subplots(figsize=(2, 4))
# ax = plt.gca()
line = ax.plot_date(a.index, a.values, '.', label='a', alpha=0.5, linewidth=1)
ax.tick_params('y', colors='k')
ax.set_xlabel('Date')
ax.set_ylabel('Frequency')
ax.set_title('Daily Games')
ax.tick_params('y', colors='k')
ax.grid(b=True, which='major', color='w', linewidth=1.0)
ax.grid(b=True, which='minor', color='w', linewidth=0.5)
ax.yaxis.grid(True)
ax.get_xaxis().set_minor_locator(mpl.ticker.AutoMinorLocator())
ax.set_xticklabels(ax.xaxis.get_majorticklabels(),
rotation=70)
ax.set_xticklabels(ax.xaxis.get_minorticklabels(),
rotation=70)
plt.xticks(rotation=70)
plt.show()
This is producing a graph like so:
I've tried all manner of rearranging but I can't get both minor and major labels for the date to plot.
I'd like to have each month labelled at 70 degrees. How can I adjust what I have to do so?
You could use the AutoDateLocator() as follows:
import seaborn as sns
import matplotlib as mpl
import matplotlib.pyplot as plt
import pandas as pd
sns.set()
a = pd.DataFrame([
('2008-10-28', 20.0), ('2008-11-04', 25.0), ('2008-11-11', 20.0),
('2008-11-18', 40.0), ('2008-11-25', 35.0), ('2008-12-02', 35.0)], columns=['Date', 'Frequency'])
a['Date'] = pd.to_datetime(a['Date'], format='%Y-%m-%d')
fig, ax = plt.subplots(figsize=(5, 5))
# ax = plt.gca()
line = ax.plot_date(a.Date, a.Frequency, '.', label='a', alpha=0.5, linewidth=1)
ax.tick_params('y', colors='k')
ax.set_xlabel('Date')
ax.set_ylabel('Frequency')
ax.set_title('Daily Games')
ax.tick_params('y', colors='k')
ax.grid(b=True, which='major', color='w', linewidth=1.0)
ax.grid(b=True, which='minor', color='w', linewidth=0.5)
ax.yaxis.grid(True)
xtick_locator = mpl.dates.AutoDateLocator()
xtick_formatter = mpl.dates.AutoDateFormatter(xtick_locator)
ax.xaxis.set_major_locator(xtick_locator)
ax.xaxis.set_major_formatter(xtick_formatter)
fig.subplots_adjust(bottom=0.24)
plt.xticks(rotation=70)
plt.show()
This would then display as:
From #MartinEvans suggestion to use AutoDateLocator() I looked up more of the matplotlib documentation and found matplotlib.dates.MonthLocator along with the WeekdayLocator. This allowed tuning the major and minor xticks to change the format and appearance as required.
I then used this answer to set their rotation.
fig, ax = plt.subplots(figsize=(2, 4))
# ax = plt.gca()
line = ax.plot_date(a.Date, a.Frequency, '.', label='a', alpha=0.5, linewidth=1)
ax.tick_params('y', colors='k')
# ax.xticks(rotation=70)
ax.set_xlabel('Date')
# ax.xlabel('Date')
ax.set_ylabel('Frequency')
ax.set_title('Daily Games')
ax.tick_params('y', colors='k')
ax.grid(b=True, which='major', color='w', linewidth=1.0)
ax.grid(b=True, which='minor', color='w', linewidth=0.5)
ax.yaxis.grid(True)
xtick_locator = mpl.dates.MonthLocator(interval=1)
xtick_formatter = mpl.dates.AutoDateFormatter(xtick_locator)
ax.xaxis.set_major_locator(xtick_locator)
ax.xaxis.set_major_formatter(xtick_formatter)
xtick_locator = mpl.dates.WeekdayLocator(byweekday=3)
xtick_formatter = mpl.dates.AutoDateFormatter(xtick_locator)
ax.xaxis.set_minor_locator(xtick_locator)
ax.xaxis.set_minor_formatter(xtick_formatter)
plt.setp(ax.xaxis.get_minorticklabels(), rotation=90, size=10)
plt.setp(ax.xaxis.get_majorticklabels(), rotation=90, size=7)
fig.subplots_adjust(bottom=0.24)
plt.show()