Make layers in the same graph in Python - python

I have three types of data that are equivalent to the monthly total, I need to create a stacked area chart that has a layer of a column chart on top showing the same value per month. I managed to make the two graphs with matplot but it shows me them separately.
data1=[13,17,19,20,23,21,27,25]
data2=[7,6,8,9,8,9,9,9]
data3=[53,45,53,61,59,67,69,68]
mes=["Enero","Febrero","Marzo","Abril","Mayo", "Junio", "Julio", "Agosto"]
# Basic stacked area chart.
pal = ["#b5030f", "#efb810", "#0a497b"]
plt.figure(figsize=(9,7))
plt.stackplot(mes,data3, data2, data1, colors=pal)
plt.legend(loc='upper left')
# Bar plot
plt.figure(figsize=(9,7))
plt.bar(mes,data3,color="#5AAB61")
plt.bar(mes,data2,color="#5AAB61",bottom=np.array(data3))
plt.bar(mes,data1,color="#5AAB61",bottom=np.array(data3)+np.array(data2))
plt.legend(loc="lower left",bbox_to_anchor=(0.8,1.0))
plt.show()

Related

Graph bars stacked and I need them separated into individual bars

I have the following code, which almost does what I need it to do. I am graphing the importance of each feature for two different models on the same graph for comparison. I can't seem to get them to show side by side as two separate bars. I am fairly new to python and brand new to this forum. here is the code:
def plot_importances1(model1, feature_names1, label1, model2=None,feature_names2=None, label2=None):
if model2 is None:
importances1 = model1.feature_importances_
indices1 = np.argsort(importances1)
plt.figure(figsize=(8, 8)) # Set figure size
# plot the first list of feature importances as a horizontal bar chart
plt.barh(range(len(indices1)), importances1[indices1], color="violet", align="center", label=label1)
# set the y-axis tick labels to be the feature names
plt.yticks(range(len(indices1)), [feature_names1[i] for i in indices1])
else:
importances1 = model1.feature_importances_
indices1 = np.argsort(importances1)
importances2 = model2.feature_importances_
indices2 = np.argsort(importances2)
plt.figure(figsize=(8, 8)) # Set figure size
# plot the first list of feature importances as a horizontal bar chart
plt.barh(range(len(indices1)), importances1[indices1], color="violet", align="center", label=label1)
# plot the second list of feature importances as a horizontal bar chart
plt.barh(range(len(indices2)), importances2[indices2], color="orange", align="center", label=label2)
# set the y-axis tick labels to be the feature names
plt.yticks(range(len(indices1)), [feature_names1[i] for i in indices1])
# add a title and x- and y-axis labels
plt.title("Feature Importances")
plt.xlabel("Relative Importance")
plt.ylabel("Feature")
# add a legend to the plot
plt.legend()
# set the tick locations and labels for the first bar graph
plt.gca().tick_params(axis='x', which='both', length=0)
plt.gca().xaxis.set_ticks_position('top')
plt.gca().xaxis.set_label_position('top')
# set the tick locations and labels for the second bar graph
plt.twinx()
plt.gca().tick_params(axis='x', which='both', length=0)
plt.gca().xaxis.set_ticks_position('bottom')
plt.gca().xaxis.set_label_position('bottom')
plt.show()
Then I call the function:
plot_importances1(
dTree_treat_out,
list(X1_train),
"Outliers present",
dTree,
list(X_train),
"No outliers",
)
The two bars are both showing, but I can't get them to separate completely and I am getting this error:
Output for the code
I have ran several version of this, including one that does not return the matplotlib error. The problem with the other function definitions that I have is that the bars are stacked and I can't see both of them. If I knew how to make one less opaque? I am super stuck. I so not want them stacked, I need the first one to be its own graph with the second one NEXT to it, not overlaying or stacked on top, similar to the image I uploaded, but the bars need to be completely separated.
Any input to fix this issue will be greatly appreciated.

How to create a single series bar graph with legends using Python

How do I visualize the below dataframe in Python. I wish to visualize the data in a bar chart where the Year_of_Release is the X axis, Global_Sales is the bar height & the genre is the legend. The bar has to be colored separately for each Genre. I have shared a sample of what I'm looking for. The sample graph was created on R using GGPLOT.
Below are the column definitions
Year_of_Release - Year of Release
Genre - Game Genre
Global_Sales - Revenue made by a Genre in that given year
Images of the data frame & desired Bar plot as as below
Data Frame:
Desired Bar Chart:
you can use the code below to plot that you need...
fig, ax = plt.subplots(figsize=(12,6))
sns.set_theme(style="darkgrid")
ax=sns.barplot(x="Year_of_Release", y="Global_Sales", hue="Genre", dodge=False, palette="rocket", data=df)
plt.xticks(rotation=90)
ax.grid(True)
ax.legend(loc='upper left')
plt.show()
Plot
with dummy data
...

Creating a bar chart with 2 y axes from lists using matplotlib

I need to make the following chart: Number of Companies, Donations vs Year as a bar chart.
The following is my data:
Year = [2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018]
No_Companies = [123558,132335,147606,155790,161211,169784,174599,183888,198727,207317,217357,228996]
Donations=[144932,304607,642328,870509,1205382,1094624,2089240,2325322,2387036,3096069,4204255,3500766]
From what I have seen from other questions, most seem to have either their data in a dataframe or a list like [[x1,y1],[x2,y2]].
How can I get the chart I need from the data I have?
You can check this link out: Plot bar and line in same plot, different y-axes using matplotlib (no pandas)
The implementation can be done as follows:
plt.figure(1, figsize=(10,10))
barchart = plt.bar(Year, No_Companies, color='red')
plt.ylabel('No Companies')
plt.twinx()
barchart1 = plt.bar(Year, Donations, color='blue')
plt.ylabel('Donations')
Graph

How to create a double axis for one graph

I'm trying to have two y-axes with the same x-axis.
This is what I have tried. But the suicide rates are not showing up on the graph.
I'm new to this, so I was wondering if anyone could spot why its not showing.
The picture is supposed to look like this with suicide rates in red and trust in blue with country as the x-axis
def suicidevstrustcountryplot(dat):
# Does income index change trust for female led countries?
# dat.plot(x ='Country', y='Income', kind = 'line')
# plt.show()
# create figure and axis objects with subplots()
fig,ax = plt.subplots()
# make a plot
ax.plot(dat.Country, dat.Trust, color="red", marker="o")
# set x-axis label
ax.set_xlabel("Country",fontsize=14)
for label in ax.get_xticklabels():
label.set_rotation(90)
label.set_ha('right')
# set y-axis label
ax.set_ylabel("Trust",color="red",fontsize=14)
# twin object for two different y-axis on the sample plot
ax2=ax.twinx()
# make a plot with different y-axis using second axis object
ax2.plot(dat.Country, dat.Trust,color="blue",marker="o")
ax2.set_ylabel("Suicide rate",color="blue",fontsize=14)
plt.show()
# save the plot as a file
fig.savefig('two_different_y_axis_for_single_python_plot_with_twinx.jpg',
format='jpeg',
dpi=100,
bbox_inches='tight')
suicidevstrustcountryplot(Femaletrust)
suicidevstrustcountryplot.suicidevstrustcountryplot.sort_values(ascending=False)[:10].plot(kind='scatter' ,title='Country')

Label Matplotlib subplot y-axes with list of strings

I'm using Matplotlib to create 2 side-by-side horizontal bar charts showing regression coefficient importance across several words. I'd like to label the y-axes with each word in the list.
Every other word is appended to the y-axis when I try this:
# plot word importance bar graphs
fig, axes = plt.subplots(1,2,figsize=(5,10))
plt.subplots_adjust(wspace = 1)
axes[0].set_title('Low revenue')
axes[0].invert_yaxis()
axes[0].barh(np.arange(len(lowrev_topten)), lowrev_topten['Coefficient'])
axes[0].set_yticklabels(list(lowrev_topten['Word']))
axes[0].set_xlabel('Coefficient')
axes[1].set_title('High revenue')
axes[1].invert_yaxis()
axes[1].barh(np.arange(len(highrev_topten)), highrev_topten['Coefficient'])
axes[1].set_yticklabels(list(highrev_topten['Word']))
axes[1].set_xlabel('Coefficient')
However, when I remind it that I'd like to have 10 ticks for 10 words (plt.yticks(np.arange(0,10))), it fixes the second subplot:
# plot word importance bar graphs
fig, axes = plt.subplots(1,2,figsize=(5,10))
plt.subplots_adjust(wspace = 1)
plt.yticks(np.arange(0,10))
axes[0].set_title('Low revenue')
axes[0].invert_yaxis()
axes[0].barh(np.arange(len(lowrev_topten)), lowrev_topten['Coefficient'])
axes[0].set_yticklabels(list(lowrev_topten['Word']))
axes[0].set_xlabel('Coefficient')
axes[1].set_title('High revenue')
axes[1].invert_yaxis()
axes[1].barh(np.arange(len(highrev_topten)), highrev_topten['Coefficient'])
axes[1].set_yticklabels(list(highrev_topten['Word']))
axes[1].set_xlabel('Coefficient')
How do I get both subplots to have the proper y-tick labels?
Seems like you just need to set_yticks for each subplot.
fig, axes = plt.subplots(1,2,figsize=(5,10))
...
axes[0].set_yticks(np.arange(0,10))
axes[1].set_yticks(np.arange(0,10))

Categories

Resources