Issue
I want to make an overlayed figure using a boxplot + barplot. I managed to overlap the two plots but I can't set the labels of the barplot.
Sample code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1234)
df = pd.DataFrame(np.random.randn(10, 4)+3,
columns=['Col1', 'Col2', 'Col3', 'Col4'])
boxplot = df.boxplot(column=['Col1', 'Col2', 'Col3'])
ax = plt.gca()
b = ax.bar(0,5)
How can I add a label to the boxplot? (e.g. 'Col0') I've tried the functions set_label()
, bar_label()
and set_xticklabels()
but I didn't manage to solve the issue.
Related threads:
Overlay box plots on bars matplotlib/python
How to add value labels on a bar chart
Solution
You must use plt.xticks() which adds the label.
# Import modules
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# --------------------------- #
# Creating dataframe
df = pd.DataFrame({
'Col1': [1, 2, 3],
'Col2': [3, 4, 5],
'Col3': [2, 1, 2]
})
# Define the axes of the plot
ax = plt.subplot()
# Add the boxplot
boxplot = df.boxplot()
# Add the barchart
ax.bar(0, 5)
# Store all the x-ticks label in this tuple
objects = ('Col0', 'Col1', 'Col2', 'Col3')
y_pos = np.arange(len(objects)) # The position of the labels
# Add the ticks to the plot
plt.xticks(y_pos, objects)
plt.show()
Answered By - Aradhna Sonia
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.