Seaborn stacking bars in multiple countplots located within a subplot [duplicate] - python

This question already has answers here:
How to have clusters of stacked bars
(10 answers)
Closed 4 years ago.
Is there a way to stack the bars in countplot so each bar contains two colors.
My code so far:
fig, axes = plt.subplots(4, 4, figsize=(15,13), sharex=True)
axes = axes.flatten()
object_bol = df.dtypes == 'object'
for ax, catplot in zip(axes, df.dtypes[object_bol].index):
sns.countplot(y=catplot, data=df, ax=ax, hue = "Attrition")
plt.tight_layout()
plt.show()
My current visualization is below along with the stacked graph I am looking to implement.

You can pass keyword arguments to plt.bar from seaborn.countplot.
You can, therefore use the bottom argument. For example (using plt.bar):
x = np.arange(0,11,1)
y = x**2
plt.bar(x, y)
plt.bar(x, y, bottom=y)
plt.xlabel('x')
plt.ylabel('y')
Gives:

Related

Seeking explaination of why my stacked bar chart bars does not stack but overlap instead? [duplicate]

This question already has answers here:
Horizontal stacked bar plot and add labels to each section
(3 answers)
Horizontal stacked bar chart in Matplotlib
(4 answers)
Closed 3 months ago.
Using MatPlotLib in Python, i have tried this:
labels = range(len(df["Investigations"])) #column vector of strings - hid for the example's sake
normals = df["No signs of pathology"] #column vector of integers
abnormals = df["Abnormal"] #column vector of integers
width = 0.5
fig, ax = plt.subplots()
#set size
fig.set_figheight(7.5)
#labels
ax.barh(labels, normals, width, label='No signs of pathology', color='blue')
ax.barh(labels, abnormals, width, label='Abnormal', color='red')
# grid lines
ax.set_axisbelow(True)
ax.xaxis.grid(color='gray', linestyle='solid', alpha=0.2)
#read top-to-bottom
#Title and legend
ax.set_title('Investigations')
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),
fancybox=True, shadow=True, ncol=5)
plt.show()
This gives me a chart that looks like the attachement, but i can see that the red, and the blue bars does not stack but overlaps. They should be stacking. Can anyone help me solve this issue? :)
Example of stacked bar chart

Problem plotting spectrogram colorbar in matplotlib [duplicate]

This question already has answers here:
How to plot in multiple subplots
(12 answers)
Closed 1 year ago.
I want to make a subplot using the input data
I think this is just a question of passing the spectrogram's "mappable" to plt.colorbar() so that it knows what to make a colourbar for. The tricky thing is that it's a bit buried in an attribute of the spectrogram Axes:
fig, (ax1, ax2, ax3) = plt.subplots(3, sharex=True)
ax1.plot(time, data1[0].data)
ax2.plot(time, data2.data)
spec = data2.spectrogram(axes=ax3, # <-- Assign a name.
show=True,
samp_rate=20,
per_lap=0.5,
wlen=30,
log=True,
cmap='plasma', # <-- Don't use jet :)
clip=(0.05, 0.2),
)
plt.xlabel('Time')
plt.ylabel('Frequency')
# More flexibility with the positioning:
cbar_ax = fig.add_axes([0.2, 0.0, 0.6, 0.05]) # Left, bottom, width, height.
cbar = fig.colorbar(spec.collections[0], # <-- Get the mappable.
cax=cbar_ax,
orientation='horizontal')
cbar.set_label('Colorbar label')
plt.show()
This also shows how to position the colorbar where you want. And I changed your colourmap to plasma because you shouldn't use jet.

Increasing the h-size of plots in plt.subplot() inside a loop - Python [duplicate]

This question already has answers here:
How do I change the size of figures drawn with Matplotlib?
(14 answers)
Closed 4 years ago.
I have this code:
for i in ["Dia", "DiaSemana", "Mes", "Año", "Feriado"]:
plt.subplot(1,2,1)
sns.boxplot(x=i, y="Y", data=df)
plt.subplot(1,2,2)
sns.boxplot(x=i, y="Temp", data=df)
plt.tight_layout()
plt.show()
It gives me all the plots I need. Here is one-time loop:
As you can see, the x axis is overlapped and I'm trying to increase the horizontal size of each plot in order to have a better visualization.
You are limited by the width of your figure. You can make your figure wider with the figsize attribute. You can "grab" your figure by either explicitly defining it (plt.figure) or getting the current figure (plt.gcf).
However, I prefer is using plt.subplots to define both figure and axes:
for i in ["Dia", "DiaSemana", "Mes", "Año", "Feriado"]:
fig, axes = plt.subplots(ncols=2, figsize=(15, 5)) # set width of figure and define both figure and axes
sns.boxplot(x=i, y="Y", data=df, ax=axes[0])
sns.boxplot(x=i, y="Temp", data=df, ax=axes[1])
plt.tight_layout()
plt.show()
Alternatively, you could decrease the number of ticks in the x axis.

python matplotlib markerscale for area plot [duplicate]

This question already has answers here:
increase the linewidth of the legend lines in matplotlib
(4 answers)
Closed 5 years ago.
What I want to do is a plot of generation and demand in an electricity grid with Matplotlib in Python. This is my code:
fig,ax = plt.subplots(figsize=(14,8))
generation.plot(kind="area", ax=ax, linewidth=1, alpha=0.9)
load.plot(kind="area", ax=ax, linewidth=1, alpha=0.9)
labels = ['Erzeugung', 'Last']
ax.legend(labels, ncol=4, loc="best", markerscale=10)
ax.set_ylabel("GW")
ax.set_xlabel("")
plt.tight_layout()
The result looks like this:
My question is about the markerscale: Why doesn't it work with this kind of plot? The problem is the bad visibility of the marker in the legend, it would be much better with a thicker line or even a box. And this without increasing the line width of the lines. Any ideas?
You can set the line size manually after creation as follows:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
fig, ax = plt.subplots(figsize=(14,8))
generation = pd.DataFrame(np.random.randint(10, 14, 10))
load = pd.DataFrame(np.random.randint(2, 5, 10))
generation.plot(kind="area", ax=ax, linewidth=1, alpha=0.9)
load.plot(kind="area", ax=ax, linewidth=1, alpha=0.9)
labels = ['Erzeugung', 'Last']
legend = ax.legend(labels, ncol=4, loc="best")
for handle in legend.legendHandles:
handle.set_linewidth(3.0)
ax.set_ylabel("GW")
ax.set_xlabel("")
plt.tight_layout()
plt.show()
Giving you something like:

Python Matplotlib How to create subplots? [duplicate]

This question already has answers here:
How to remove gaps between subplots in matplotlib
(6 answers)
Closed 6 years ago.
I am having quite a bit of trouble understanding how to create good subplots. I want to create a figure that is similar to the one shown below. Does anyone know how I could set up a similar template as this?
Also, how would I include these points with error bars in the subplots?
This is my code for the error bars:
mass, p, errp, errl = np.loadtxt('/Users/shawn/Desktop/vika1.dat', usecols = [0, 10, 11, 12], unpack = True)
plt.errorbar(mass, np.log10(p) - 4, yerr = [np.log10(p) - np.log10(p-errl), np.log10(p + errp) - np.log10(p)], fmt = 'o', markerfacecolor = 'w', markeredgecolor = 'k', ecolor = 'k')
You could use sharex and sharey to share the axes. The following will give the layout you want. You can then plot individual subplots using your specific plot funcitons.
Updated complete code below
import numpy as np
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True)
X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
C, S = np.cos(X), np.sin(X)
axes[0,0].plot(X, C, color="blue", linewidth=1.0, linestyle="-")
axes[0,1].plot(X, C, color="orange", linewidth=1.0, linestyle="-")
axes[1,0].plot(X, C, color="green", linewidth=1.0, linestyle="-")
axes[1,1].plot(X, C, color="red", linewidth=1.0, linestyle="-")
plt.subplots_adjust(wspace=0,hspace=0)
plt.show()
Can't understand why someone has downvoted me for the initial answer...
The below lines would prune the min value for both x and y axes thereby avoiding label overlaps
from matplotlib.ticker import MaxNLocator
axes[1,1].yaxis.set_major_locator(MaxNLocator(prune='lower'))
axes[1,1].xaxis.set_major_locator(MaxNLocator(prune='lower'))

Categories

Resources