Visualise different areas on the axes in a matplotlib python plot - python-3.x

I would like to generate a plot like this in Python:
I am primarily interested in the possibility of inserting the pink and green areas into the plot in order to highlight different ranges. Area1-3 should get different colours and names later.
Thanks a lot!
PS: my Phython code atm is:
fig3, ax3 = plt.subplots()
plot3 = ax3.scatter(nocore[0,:],nocore[1,:],c=nocore[2,:], s=3, cmap='seismic', label='Group X')
ax3.set_xlabel("X")
ax3.set_ylabel("Y")
ax3.legend(loc='upper center', bbox_to_anchor=(0.5, 1.15))
plt.ylim(ymin=45, ymax=362)
plt.ylim(ymin=0, ymax=320)
fig3.colorbar(plot3, ax=ax3, label ='Colorrange')
plt.savefig('nocore.png', dpi=300)
plt.show()
Not sure what to do or what is the best way of doing it.

Related

Spacing out dates on the X-Axis in Matplotlib

I'm analyzing coronavirus data in my country and I want to plot the data on new deaths, and total deaths in one plot. Initially I plotted it using the inbuilt plot function on the dataframe.
reports.plot(x='date', y='new_deaths')
reports.plot(x='date', y='total_deaths')
plt.xlabel('date')
plt.ylabel('cases')
plt.show()
Which yielded these images.
However, I wanted to change the legends, and have them to be in one plot instead so I went ahead and used plt.subplot(111).
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(ph_reports_april.date, ph_reports_april.new_deaths, label='New Deaths')
ax.plot(ph_reports_april.date, ph_reports_april.total_deaths, label='Total Deaths')
plt.xlabel('Date')
plt.ylabel('Cases')
ax.legend()
plt.show()
It got the job done except for one little problem.
The dates are congested. Is there a way to have the date similar to how the dataframe.plot() function works? I've browse through this site and haven't found anything of value regarding on spacing out the values of date in the x-axis.

How to change color in pie chart using Matplotlib

I am trying to make v1 as blue, v2 as orange, v3 green and v4 as light grey
I tried going through documentation but cannot understand how to define color in piechart. Thank you for help.
I am using few line of codes of generate a piechart
where vol1 = v1,v2,v3,v4
plt.pie(vol1,labels = vollabels, autopct="%0.2f%%")
plt.legend(title="Normalized Volumes",loc="upper left", fontsize=14)
plt.axis
plt.show()
If you want to have control over which colors your pie chart contains, while at the same time not fall out of matplotlib's convenient handling of colour maps, you might want to have a look at documentation example Nested pie charts. Extracted highlights:
import matplotlib.pyplot as plt
import numpy as np
Retrieve a named colour map and "hand-pick", using a numbered range, suitable colors. The index picking in inner_colors matches hues for a larger numbers of data points in the inner circle:
cmap = plt.get_cmap("tab20c")
outer_colors = cmap(np.arange(3)*4)
inner_colors = cmap(np.array([1, 2, 5, 6, 9, 10]))
The actual plotting, including some customisation, is then straightforward:
fig, ax = plt.subplots()
size = 0.3
vals = np.array([[60., 32.], [37., 40.], [29., 10.]])
ax.pie(vals.sum(axis=1), radius=1, colors=outer_colors,
wedgeprops=dict(width=size, edgecolor='w'))
ax.pie(vals.flatten(), radius=1-size, colors=inner_colors,
wedgeprops=dict(width=size, edgecolor='w'))
Bonus content in the linked location: how to achieve the same result using a bar plot, but using polar coordinates. That way, one has more flexibility over the exact design, if one's goals diverge from the defaults assumed in pie.

Why does x = df.index is different than x=ax.get-xticks() for twin-x plot in seaborn?

I am trying to do a plot sharing the X axis, representing time (YYYYMM) and 2 y-axis one representing a count (for bars) and the other representing the evolution of a percentage.
Desired outcome:
So I did manage to do the plot I wanted, but I am not really understanding WHY.
The following code is the one that generated the plot above
f,ax=plt.subplots(figsize=(10,6))
sns.barplot(data=df,x=df.index,y='solicitudes',color=color,label='solicitudes',ax=ax)
ax2 = ax.twinx()
sns.lineplot(data=df, x= ax.get_xticks(), y='pctMalos',ax=ax2,color='red',lw=3,label='pct')
plt.show()
On the other hand, this code
f,ax=plt.subplots(figsize=(10,6))
sns.barplot(data=df,x=df.index,y='solicitudes',color=color,label='solicitudes',ax=ax)
ax2 = ax.twinx()
sns.lineplot(data=df, x= df.index, y='pct',ax=ax2,color='red',lw=3,label='pct')
plt.show()
Generates this other image
As long as I can see the only difference is that in one I "get the x axis" and in the second one I use the same x (i.e. calling df.index, which works fine for only 1 plot)
Yet, the second one breaks.
I am also having trouble with x-ticks-labels, but I believe there is something quite basic about Seaborn that I am missing.. do you know what it is?
Thank you very much in advance to anyone who could help me!

I am trying to move the x axis from bottom to top in matplotlib. But xaxis.set_ticks_position('top') does not seem to work as it should?

I am plotting a log using matplotlib and would like my x axis to be position at the top of the plot rather than bottom.
I tried xaxis.set_ticks_position('top') but it did not work. However xaxis.set_label_position('top') worked for the label.
from matplotlib import gridspec
# creating the figure
fig=plt.figure(figsize=(12,10))
# adding the title
fig.suptitle('Volume of Clay from different methods',fontsize=14)
# creating the axes
gs=gridspec.GridSpec(4,3)
ax1=fig.add_subplot(gs[:,0])
ax2=fig.add_subplot(gs[0,1])
ax3=fig.add_subplot(gs[1,1])
ax4=fig.add_subplot(gs[2,1])
ax5=fig.add_subplot(gs[3,1])
ax6=fig.add_subplot(gs[:,2],sharey=ax1)
# Plotting graph for GR,SP
ax1.invert_yaxis()
ax1.xaxis.set_label_position('top')
ax1.xaxis.set_ticks_position('top')
ax1.grid(True)
ax1.set_ylabel('DEPTH')
ax1.set_xlabel('GR[api]',color='green')
ax1.tick_params('x',colors='green')
ax1.spines['top'].set_position(('outward',0))
ax1.plot(data.GR,data.index, color='green')
ax11=ax1.twiny()
ax11.plot(data.SP,data.index,color='blue')
ax11.set_xlabel("SP[mV]",color='blue')
ax11.spines['top'].set_position(('outward',40))
plt.show()
i am expecting the x axis for the GR curve in green to be on top but it remains in the bottom instead.
I think i found out what's going on thanks to #ImportanceOfBeingErnest
ax11.ax1.twiny() is overwriting ax1
i've fix the code as below.
from matplotlib import gridspec
# creating the figure
fig=plt.figure(figsize=(12,10))
# adding the title
fig.suptitle('Volume of Clay from different methods',fontsize=14)
fig.subplots_adjust(top=0.9,wspace=0.3, hspace=0.3)
# creating the axes
gs=gridspec.GridSpec(4,3)
ax1=fig.add_subplot(gs[:,0])
ax1.get_xaxis().set_visible(False)
ax2=fig.add_subplot(gs[0,1])
ax3=fig.add_subplot(gs[1,1])
ax4=fig.add_subplot(gs[2,1])
ax5=fig.add_subplot(gs[3,1])
ax6=fig.add_subplot(gs[:,2],sharey=ax1)
# Plotting graph for GR,SP
ax10=ax1.twiny()
ax10.invert_yaxis()
ax10.xaxis.set_label_position('top')
ax10.xaxis.set_ticks_position('top')
ax10.tick_params('x',colors='green')
ax10.spines['top'].set_position(('outward',0))
ax10.grid(True)
ax10.set_ylabel('DEPTH')
ax10.set_xlabel('GR[api]',color='green')
ax10.plot(data.GR,data.index, color='green')
ax11=ax1.twiny()
ax11.plot(data.SP,data.index,color='blue')
ax11.set_xlabel("SP[mV]",color='blue')
ax11.spines['top'].set_position(('outward',40))
If there are any better way to write this please do comment.

Bar format (kind) is not displaying the right plot (matplotlib)

I need to do a plot using three variables. One of them should be on the secondary Y axis in bar format (kind), the remaining variables (two) should be on the left axis using a simple line. However, I got the following chart:
When I use the three variables in line format I get the right plot (which is not very useful for a visual analysis):
I did a quick test using a small sample from my data (code below). I get the right pic when I use bar format for the third one.
I wonder, what is going on? Is there a problem with the data size (which I dont think so bcs I get less than 100 rows)?
df2 = pd.DataFrame({'ind':[120.29, 125.45, 127.37, 130.39, 128.30],
'var1':[129.907990, 129.571185, 129.234380, 128.897574, 128.560769],
'var2':[-0.074037, -0.031806, -0.014426, 0.011578, -0.002028]})
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
df2['ind'].plot(ax=ax1)
df2['var1'].plot(ax=ax1)
df2['var2'].plot(kind='bar', ax=ax2, color='r')
plt.show()
PD: In addition, I noted that in the third pic the line is behind the bar. How can I change that?
I found the solution for this (this link helped me a lot ). Basically, it is based on the index you set up previously.
This is the new code:
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(df2.index, df2['ind'])
ax1.plot(df2.index, df2['var1'])
ax2.bar(df2.index, df2['var2'], color='r')
plt.show()
Hope this helps.

Resources