Issue with seaborn twinx - Only one graph is displaying [duplicate] - python

This question already has answers here:
How can I make a barplot and a lineplot in the same seaborn plot with different Y axes nicely?
(2 answers)
Problem in combining bar plot and line plot (python)
(2 answers)
Closed 10 months ago.
I want to plot 2 subplot. The First subplot is using only one y-axis and is working as expected, in second subplot i want to create dual y -axis and plot line and bar plot. But seems like only barplot is rendering, Can someplease please highlight where i am going wrong ?
f,axes =plt.subplots(1,2)
sns.set_theme(style='whitegrid',palette="pastel")
sns.set(rc={'figure.figsize':(20.7,3.27)})
plt.figure(figsize=(20.7,3.27))
# Single Y-Axis in left side plot
sns.lineplot(x='date', y="visit", data=df[(df['Website'] == url)], ci= None,ax=axes[0]).set_title(url)
sns.lineplot(x='date', y="visit_industry", data=df[(df['Website'] == url)], ci= None,ax=axes[0]).set_title(url)
## Dual Y- Axis in right hand side plot.
ax2 = axes[1].twinx()
sns.lineplot(x='date', y="yoy_change", data=df[(df['Website'] == url)],color='blue',ax=ax2)
sns.barplot(x='date', y="yoy_change_industry", data=df[(df['Website'] == url)],color='black',ax=ax2)
plt.tight_layout()
plt.show()

Related

Python bar chart border overlapping horizontal bars values [duplicate]

This question already has answers here:
How can I remove the top and right axis in matplotlib?
(10 answers)
Closed 7 months ago.
enter image description here
the values of bars overlapping the borders. How to change the border so that bars with values should fit in properly
#adding following lines solved the problem
fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot(111)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)

Can a subplot within a python-Matplotlib subplots be used for bullet statements? [duplicate]

This question already has answers here:
Delete a subplot
(3 answers)
Add Empty Subplot With No Axis Ticks/Labels for Text as Subplot in Matplotlib
(1 answer)
How to write annotation outside the drawing in data coords
(2 answers)
Closed 11 months ago.
I'd like to make a [2,2] subplot of charts/graphs using the first three open plots for the graphs and the 4 spot for bullet points about the graphs/charts. Is this possible using python/matplotlib?
Take for example the code below:
plt.style.use('fivethirtyeight')
fig, axes = plt.subplots(2,2)
fig.suptitle("Owner Occupied Loss Ratio")
sns.barplot(ax = axes[0,0], x=decile_oo['decile'], y=np.round((decile_oo['NonCAT Loss Ratio']*100),2), color = 'blue')
# g.bar_label(ax.containers[0])
sns.barplot(ax = axes[0,1], x=decile_oo['decile'], y=np.round((decile_oo['NonCAT Frequency']*100),2), color = 'red')
# f.bar_label(ax.containers[0])
sns.barplot(ax = axes[1,0], x=decile_oo['decile'], y=np.round((decile_oo['NonCAT Severity']*100),2), color = 'green')
# i.bar_label(ax.containers[0])
plt.tight_layout()
plt.show()
That produced the below graphic.
I'd like that blank graph in position [1,1] to have bullet points I type out instead of a blank graph. Is this possible?

Unable to position matplotlib ax.annotate correctly [duplicate]

This question already has answers here:
How to add value labels on a bar chart
(7 answers)
Stacked Bar Chart with Centered Labels
(2 answers)
How to annotate each segment of a stacked bar chart
(1 answer)
Horizontal stacked bar plot and add labels to each section
(3 answers)
Closed 11 months ago.
in the below code, I'm trying to plot stacked bar chart of % of stoke events against the gender variable.
dfgender=df.groupby('gender')['stroke'].value_counts(normalize=True).unstack().fillna(0)
ax=dfgender.plot.bar(stacked=True,colormap='tab10',figsize=(8, 6))
plt.legend(loc="upper right", ncol=1, prop={'size': 8})
plt.title('Gender vs Stroke')
plt.xlabel("Gender")
plt.ylabel("Proportion")
for p in ax.patches:
ax.annotate(round(p.get_height(),2), (p.get_x()+p.get_width()/2, p.get_height()),ha='center',va='center',xytext=(10, 0), textcoords='offset points')
plt.show()
But as you can see, the placement of the bar labels is incorrect. 1 should be 5% and 0 should be 95%. I want the figures to be represented in percentages and be positioned in the center of the bars. Can somebody help me please?

pandas bar plots x axis behaves differently than caling Axes.bar directly [duplicate]

This question already has answers here:
plot dataframe: overlay line and bar plot doesn't work for time series index?
(1 answer)
Cannot combine bar and line plot using pandas plot() function
(1 answer)
Plot Pandas DataFrame as Bar and Line on the same one chart
(1 answer)
Problem in combining bar plot and line plot (python)
(2 answers)
pandas bar plot combined with line plot shows the time axis beginning at 1970
(2 answers)
Closed 1 year ago.
I'm plotting some time series data, using both line plots and bar plots, and I observe a quirky or annoying behavior on pandas bar plots when sharing the X axis.
On the left, a pandas line plot + a call to Axes.bar directly. This is the expected result.
On the right, a pandas line plot + a pandas bar plot. The x axis of the line plot automatically turns into a float and the line disappears somewhere, probably because the change in range or scale. Also, the x axis of the bar plot displays every single date (this can be corrected with ax[1, 1].xaxis.set_major_locator(mdates.MonthLocator()), but the result is not the same).
Is there a way to make pandas bar plots behave like raw matplotlib bar plots in this case?
Code:
# close100 and volume100 are time series with the same date index
fig, ax = plt.subplots(nrows=2, ncols=2, figsize=(12, 6))
close100.plot(ax=ax[0, 0])
ax[1, 0].bar(volume100.index, volume100.values) # Using Axes.bar
close100.plot(ax=ax[1, 0])
volume100.plot.bar(ax=ax[1, 1]) # Using Series.plot.bar
ax[1, 1].xaxis.set_major_locator(mdates.MonthLocator())

How to display a legend below graph without changing the figure size in matplotlib [duplicate]

This question already has answers here:
Creating figure with exact size and no padding (and legend outside the axes)
(2 answers)
How to put the legend outside the plot
(18 answers)
Closed 4 years ago.
I am trying to put a legend below a graph but keeping the figure size fixed.
Is this possible?
I saw How to put the legend out of matplotlib plot and https://stackoverflow.com/a/4701285/7746941 but the first one does not address fitting the legend within a predefined figure size while the second one does not do this generically (there is an example where the axes width is shrunk by 0.8 to accommodate the legend) .
Below is my current solution that anchors the legend at the bottom of the graph but the legend does not fit the figure.
I cannot figure out how to determine the height of the legend box to move the axis up by that amount.
import pandas as pd
df = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6]})
ax = df.plot(figsize=(4,4))
tight_box = ax.transAxes.inverted().transform(ax.get_tightbbox(ax.figure.canvas.get_renderer()))
leg = ax.legend(bbox_to_anchor=(0,tight_box[0][1],1,0), loc='upper center')

Categories