setting axis labels in axes from matplotlib - python

I'm trying the following code to plot some graphs:
fig = plt.figure(figsize=(10, 20))
for idx, col in enumerate(['Pclass', 'Sex']):
ax = fig.add_subplot(2, 1, idx+1)
_ = ax.set(ylabel='Counts')
_ = sns.countplot(x=col, hue='Survived', data=full, ax=ax)
The output I'm getting is:
As you can see the y label is set as the seaborn countplot default label 'count', but I want to change it to 'Counts'. I've tried the axes method set_ylabel and set with ylabel argument and got no changes in the graphs. What am I doing wrong?

Can you try the following, changing the ylabel after plotting
fig = plt.figure(figsize=(10, 20))
for idx, col in enumerate(['Pclass', 'Sex']):
ax = fig.add_subplot(2, 1, idx+1)
sns.countplot(x=col, hue='Survived', data=full, ax=ax)
ax.set_ylabel('Counts')

Related

How do I move one of the y-axis' to the right hand side in a line plot by using only Python's Matplotlib Library? [duplicate]

I'm currently trying to change the secondary y-axis values in a matplot graph to ymin = -1 and ymax = 2. I can't find anything on how to change the values though. I am using the secondary_y = True argument in .plot(), so I am not sure if changing the secondary y-axis values is possible for this. I've included my current code for creating the plot.
df.plot()
df.plot(secondary_y = "Market")
From your example code, it seems you're using Pandas built in ploting capabilities. One option to add a second layer is by using matplotlib directly like in the example "two_scales.py".
It uses
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
ax1.plot(df["..."])
# ...
ax2 = ax1.twinx()
ax2.plot(df["Market"])
ax2.set_ylim([0, 5])
where you can change the y-limits.
Setting ylim on plot does not appear to work in the case of secondary_y, but I was able to workaround with this:
import pandas as pd
df = pd.DataFrame({'one': range(10), 'two': range(10, 20)})
ax = df['one'].plot()
ax2 = df['two'].plot(secondary_y=True)
ax2.set_ylim(-20, 50)
fig = ax.get_figure()
fig.savefig('test.png')
This is a solution for showing as much y-axes as data columns the dataframe has
colors = ['tab:blue',
'tab:orange',
'tab:green',
'tab:red',
'tab:purple',
'tab:brown',
'tab:pink',
'tab:gray',
'tab:olive',
'tab:cyan']
#X axe and first Y axe
fig, ax1 = plt.subplots()
x_label = str( dataFrame.columns[0] )
index = dataFrame[x_label]
ax1.set_xlabel(x_label)
ax1.set_xticklabels(dataFrame[x_label], rotation=45, ha="right")
firstYLabel = str( dataFrame.columns[1] )
ax1.set_ylabel(firstYLabel, color = colors[0])
ax1.plot(index, dataFrame[firstYLabel], color = colors[0])
ax1.tick_params(axis='y', labelcolor = colors[0])
#Creates subplots with independet y-Axes
axS =[]
def newTwix(label, ax1, index, dataFrame):
print(label)
actualPos = len(axS)
axS.append(ax1.twinx())
axS[actualPos].set_ylabel(label, color = colors[actualPos%10 + 1])
axS[actualPos].plot(index, dataFrame[label], color=colors[actualPos%10 + 1])
axS[actualPos].tick_params(axis='y', labelcolor=colors[actualPos%10 + 1])
identation = 0.075 #would improve with a dynamic solution
p = 1 + identation
for i in range(2,len(dataFrame.columns)):
newTwix(str(dataFrame.columns[i]), ax1, index, dataFrame)
if (len(axS) == 1):
axS[len(axS)-1].spines.right.set_position(("axes", p))
else:
p = int((p + identation)*1000)/1000
axS[len(axS)-1].spines.right.set_position(("axes", p))
fig.tight_layout() # otherwise the right y-label is slightly clipped
plt.subplots_adjust(left=0.04, right=0.674, bottom=0.1)
mng = plt.get_current_fig_manager()
mng.full_screen_toggle()
plt.show()
multiple y-axes with independent scales

ytick descriptions in seaborn

I'm trying to make a heatmap a heatmap with extensive y axis descriptions.
I would like to know if there is anyways to have a second and a third layer on the y tick labels.
fig, ax = plt.subplots(figsize=(20,25))
sns.set(style="darkgrid")
colName = [r'A', r'B', r'C', r'D', r'E']
colTitile = 'Test'
rowName = [r'a', r'b', r'c', r'd']
rowsName = [r'Vegetables', r'Fruits', r'Meats', r'Cheese',
r'Candy', r'Other']
rowTitile = 'Groups'
heatmapdata= np.arange(100).reshape(24,5)
sns.heatmap(heatmapdata,
cmap = 'turbo',
cbar = True,
vmin=0,
vmax=100,
ax=ax,
xticklabels = colName,
yticklabels = rowName)
for x in np.arange(0,len(ax.get_yticks()),4):
ax.axhline(x, color = 'white', lw=2)
Is there any way to do this? Which function should I use?
Thanks!
The labels for the rows can be set up in the graph settings, but other than that, I think the annotation function is the only way to handle this. the second level group names are set using the annotation function, and the coordinate criteria are set using the axis criteria. Axis labels are added using the text function with axis criteria.
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(figsize=(10,10))
sns.set(style="darkgrid")
colName = [r'A', r'B', r'C', r'D', r'E']
colTitile = 'Test'
rowName = [r'a', r'b', r'c', r'd']
rowsName = [r'Vegetables', r'Fruits', r'Meats', r'Cheese',
r'Candy', r'Other']
rowTitle = 'Groups'
heatmapdata= np.arange(120).reshape(24,5)
sns.heatmap(heatmapdata,
cmap='turbo',
cbar=True,
vmin=0,
vmax=100,
ax=ax,
xticklabels=colName,
yticklabels=np.tile(rowName, 6))
for x in np.arange(0,ax.get_ylim()[0],4):
ax.axhline(x, color = 'white', lw=2)
for idx,g in enumerate(rowsName[::-1]):
ax.annotate(g, xy=(-100, idx*90+45), xycoords='axes points', size=14)
ax.text(x=-0.3, y=0.5, s=rowTitle, ha='center', transform=ax.transAxes, rotation=90, font=dict(size=16))
plt.show()

How to clean up x-axis values in matplotlib?

So I have the following code:
fig, ax = plt.subplots(dpi=220)
data.plot(kind='bar', y='p_1', ax=ax, color ='red')
data.plot(kind='bar', y='value_1', ax=ax, color ='blue')
ax.set_xlabel("Index values")
ax.set_ylabel("Value 1 / P_1")
#ax.legend(["Value 1, P_1"])
plt.title('Line plots')
plt.show()
Which returns the following graph:
As you can see the x-axis has some crazy stuff going on. I was wondering what went wrong and how to fix this?
Here's what you're looking for I think plt.xticks(positions, labels)
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
fig, ax = plt.subplots(dpi=220)
### used this to generate and test a new plot
data = pd.DataFrame(np.array(
[np.arange(50),
np.arange(50)]
).T).rename(columns={0: 'value_1', 1:'p_1'})
print(data)
data.plot(kind='bar', y='p_1', ax=ax, color ='red')
data.plot(kind='bar', y='value_1', ax=ax, color ='blue')
ax.set_xlabel("Index values")
ax.set_ylabel("Value 1 / P_1")
### added new code here
ticks = range(0, 50, 5)
labels = ticks
plt.xticks(ticks, labels)
#ax.legend(["Value 1, P_1"])
plt.title('Line plots')
plt.xticks(np.arange(0, len(value_1)+1, 5), np.arange(0, len(value_1)+1, 5) )
creates a tick every 5 intervals and corresponding label.

How to arrange 4 Seaborn plots in a grid (Python)?

I would like to arrange four Seaborn plots in a 2 x 2 grid. I tried the following code but I got an exception. I would also like to know how to set titles and xlabel, ylabel in the subplots and a title for the overall grid plot.
Some toy data:
df
'{"age":{"76":33,"190":30,"255":36,"296":27,"222":19,"147":39,"127":23,"98":24,"168":29,"177":39,"197":27,"131":36,"36":30,"219":28,"108":38,"198":34,"40":32,"246":24,"109":26,"117":47,"20":26,"113":24,"279":35,"120":35,"7":26,"119":28,"272":24,"66":28,"87":28,"133":28},"Less_than_College":{"76":1,"190":1,"255":0,"296":1,"222":1,"147":1,"127":0,"98":0,"168":1,"177":1,"197":0,"131":1,"36":0,"219":0,"108":0,"198":0,"40":0,"246":0,"109":1,"117":1,"20":0,"113":0,"279":0,"120":0,"7":0,"119":1,"272":0,"66":1,"87":0,"133":0},"college":{"76":0,"190":0,"255":0,"296":0,"222":0,"147":0,"127":1,"98":1,"168":0,"177":0,"197":1,"131":0,"36":1,"219":1,"108":0,"198":1,"40":1,"246":0,"109":0,"117":0,"20":1,"113":1,"279":0,"120":1,"7":1,"119":0,"272":0,"66":0,"87":1,"133":1},"Bachelor":{"76":0,"190":0,"255":1,"296":0,"222":0,"147":0,"127":0,"98":0,"168":0,"177":0,"197":0,"131":0,"36":0,"219":0,"108":1,"198":0,"40":0,"246":1,"109":0,"117":0,"20":0,"113":0,"279":1,"120":0,"7":0,"119":0,"272":1,"66":0,"87":0,"133":0},"terms":{"76":30,"190":15,"255":30,"296":30,"222":30,"147":15,"127":15,"98":15,"168":30,"177":30,"197":15,"131":30,"36":15,"219":15,"108":30,"198":7,"40":30,"246":15,"109":15,"117":15,"20":15,"113":15,"279":15,"120":15,"7":15,"119":30,"272":15,"66":30,"87":30,"133":15},"Principal":{"76":1000,"190":1000,"255":1000,"296":1000,"222":1000,"147":800,"127":800,"98":800,"168":1000,"177":1000,"197":1000,"131":1000,"36":1000,"219":800,"108":1000,"198":1000,"40":1000,"246":1000,"109":1000,"117":1000,"20":1000,"113":800,"279":800,"120":800,"7":800,"119":1000,"272":1000,"66":1000,"87":1000,"133":1000}}'
fig = plt.figure()
fig.subplots_adjust(hspace=0.4, wspace=0.4)
ax = fig.add_subplot(2, 2, 1)
ax.sns.distplot(df.Principal)
ax = fig.add_subplot(2, 2, 2)
ax.sns.distplot(df.terms)
ax = fig.add_subplot(2, 2, 3)
ax.sns.barplot(data = df[['Less_than_College', 'college', 'Bachelor', ]])
ax = fig.add_subplot(2, 2, 4)
ax.sns.boxplot(data = df['age'])
plt.show()
AttributeError: 'AxesSubplot' object has no attribute 'sns'
ax is matplotlib object that do not have sns attribute, because of this you are getting error. sns is seaborn object. If you want to use ax object with seaborn plot for your case pass parameter ax=ax in seaborn object as follows:
fig = plt.figure()
fig.subplots_adjust(hspace=0.4, wspace=0.4)
ax = fig.add_subplot(2, 2, 1)
sns.distplot(df.Principal,ax=ax)
ax = fig.add_subplot(2, 2, 2)
sns.distplot(df.terms,ax=ax)
ax = fig.add_subplot(2, 2, 3)
sns.barplot(data = df[['Less_than_College', 'college', 'Bachelor']],ax=ax)
ax.set_xticklabels(ax.get_xticklabels(), rotation=90)
ax = fig.add_subplot(2, 2, 4)
sns.boxplot(df['age'],ax=ax)
plt.show()
The plot looks like this.

How to set a secondary y-axis in Python

I'm currently trying to change the secondary y-axis values in a matplot graph to ymin = -1 and ymax = 2. I can't find anything on how to change the values though. I am using the secondary_y = True argument in .plot(), so I am not sure if changing the secondary y-axis values is possible for this. I've included my current code for creating the plot.
df.plot()
df.plot(secondary_y = "Market")
From your example code, it seems you're using Pandas built in ploting capabilities. One option to add a second layer is by using matplotlib directly like in the example "two_scales.py".
It uses
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
ax1.plot(df["..."])
# ...
ax2 = ax1.twinx()
ax2.plot(df["Market"])
ax2.set_ylim([0, 5])
where you can change the y-limits.
Setting ylim on plot does not appear to work in the case of secondary_y, but I was able to workaround with this:
import pandas as pd
df = pd.DataFrame({'one': range(10), 'two': range(10, 20)})
ax = df['one'].plot()
ax2 = df['two'].plot(secondary_y=True)
ax2.set_ylim(-20, 50)
fig = ax.get_figure()
fig.savefig('test.png')
This is a solution for showing as much y-axes as data columns the dataframe has
colors = ['tab:blue',
'tab:orange',
'tab:green',
'tab:red',
'tab:purple',
'tab:brown',
'tab:pink',
'tab:gray',
'tab:olive',
'tab:cyan']
#X axe and first Y axe
fig, ax1 = plt.subplots()
x_label = str( dataFrame.columns[0] )
index = dataFrame[x_label]
ax1.set_xlabel(x_label)
ax1.set_xticklabels(dataFrame[x_label], rotation=45, ha="right")
firstYLabel = str( dataFrame.columns[1] )
ax1.set_ylabel(firstYLabel, color = colors[0])
ax1.plot(index, dataFrame[firstYLabel], color = colors[0])
ax1.tick_params(axis='y', labelcolor = colors[0])
#Creates subplots with independet y-Axes
axS =[]
def newTwix(label, ax1, index, dataFrame):
print(label)
actualPos = len(axS)
axS.append(ax1.twinx())
axS[actualPos].set_ylabel(label, color = colors[actualPos%10 + 1])
axS[actualPos].plot(index, dataFrame[label], color=colors[actualPos%10 + 1])
axS[actualPos].tick_params(axis='y', labelcolor=colors[actualPos%10 + 1])
identation = 0.075 #would improve with a dynamic solution
p = 1 + identation
for i in range(2,len(dataFrame.columns)):
newTwix(str(dataFrame.columns[i]), ax1, index, dataFrame)
if (len(axS) == 1):
axS[len(axS)-1].spines.right.set_position(("axes", p))
else:
p = int((p + identation)*1000)/1000
axS[len(axS)-1].spines.right.set_position(("axes", p))
fig.tight_layout() # otherwise the right y-label is slightly clipped
plt.subplots_adjust(left=0.04, right=0.674, bottom=0.1)
mng = plt.get_current_fig_manager()
mng.full_screen_toggle()
plt.show()
multiple y-axes with independent scales

Categories

Resources