Set minor ticks in all log-log subplots - python

I have a figure with two subplots in log-log scale. I would like to plot the minor ticks as well. Even though I have applied different solutions from Stack Overflow, my figure does not look as I want.
One of the solutions I have modified comes from ImportanceOfBeingErnest and the code looks like this:
fig, ((ax1, ax2)) = plt.subplots(1, 2, figsize=(8, 5), sharey=True)
# First plot
ax1.loglog(PLOT1['X'], PLOT1['Y'], 'o',
markerfacecolor='red', markeredgecolor='red', markeredgewidth=1,
markersize=1.5, alpha=0.2)
ax1.set(xlim=(1e-4, 1e4), ylim=(1e-8, 1e2))
ax1.set_xscale("log"); ax1.set_yscale("log")
ax1.xaxis.set_major_locator(matplotlib.ticker.LogLocator(base=10.0, numticks=25))
ax1.yaxis.set_major_locator(matplotlib.ticker.LogLocator(base=10.0, numticks=25))
locmaj = matplotlib.ticker.LogLocator(base=10,numticks=25)
ax1.xaxis.set_major_locator(locmaj)
locmin = matplotlib.ticker.LogLocator(base=10.0,subs=(0.2,0.4,0.6,0.8),numticks=25)
ax1.xaxis.set_minor_locator(locmin)
ax1.xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())
locmaj = matplotlib.ticker.LogLocator(base=10,numticks=25)
ax1.yaxis.set_major_locator(locmaj)
locmin = matplotlib.ticker.LogLocator(base=10.0,subs=(0.2,0.4,0.6,0.8),numticks=25)
ax1.yaxis.set_minor_locator(locmin)
ax1.yaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())
ax1.set_xlabel('X values', fontsize=10, fontweight='bold')
ax1.set_ylabel('Y values', fontsize=10, fontweight='bold')
# Plot 2
ax2.loglog(PLOT2['X'], PLOT2['Y'], 'o',
markerfacecolor='blue', markeredgecolor='blue', markeredgewidth=1,
markersize=1.5, alpha=0.2)
ax2.set(xlim=(1e-4, 1e4), ylim=(1e-8, 1e2))
ax2.xaxis.set_major_locator(matplotlib.ticker.LogLocator(base=10.0, numticks=25))
ax2.yaxis.set_major_locator(matplotlib.ticker.LogLocator(base=10.0, numticks=25))
locmaj = matplotlib.ticker.LogLocator(base=10,numticks=25)
ax2.xaxis.set_major_locator(locmaj)
ax2.yaxis.set_major_locator(locmaj)
locmin = matplotlib.ticker.LogLocator(base=10.0,subs=(0.2,0.4,0.6,0.8),numticks=25)
ax2.xaxis.set_minor_locator(locmin)
ax2.yaxis.set_minor_locator(locmin)
ax2.xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())
ax2.yaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())
ax2.set_xlabel('X values', fontsize=10, fontweight='bold')
ax2.set_ylabel('Y values', fontsize=10, fontweight='bold')
ax2.minorticks_on()
plt.show()
The plot I get is the following. As you can see, the minor ticks only appear on the x-axis from ax1.
How can I set the minor ticks in both subplots and both axis (x and y)?
Thank you so much.

Related

Legend in subplots() for vertical lines Matplotlib.pyplot Python

I am trying to do EDA with the Kaggle dataset link
I made a plot with 3 subplots and have plotted 3 vertical lines on the basis of mean, median and mode. is there any way to show these 3 lines in a legend?
This is my code
def plott(data):
fig, axes = plt.subplots(3, sharex=True, figsize=(15, 15),gridspec_kw={"height_ratios": (1, 0.2, 0.6)})
fig.suptitle('Spread of Data for ' + data.name, fontsize=20, fontweight='bold')
sns.histplot(data, kde=True, binwidth=1, ax=axes[0])
sns.boxplot(x=data, orient='h', ax=axes[1])
sns.violinplot(x=data, ax=axes[2])
axes[0].set_xlabel('')
axes[1].set_xlabel('')
axes[2].set_xlabel('')
axes[0].axvline(data.mean(), color='r', linewidth=2, linestyle='solid')
axes[0].axvline(data.median(), color='r', linewidth=2, linestyle='dashed')
axes[0].axvline(data.mode()[0], color='r', linewidth=2, linestyle='dotted')
axes[1].axvline(data.mean(), color='r', linewidth=2, linestyle='solid')
axes[1].axvline(data.median(), color='r', linewidth=2, linestyle='dashed')
axes[1].axvline(data.mode()[0], color='r', linewidth=2, linestyle='dotted')
axes[2].axvline(data.mean(), color='r', linewidth=2, linestyle='solid')
axes[2].axvline(data.median(), color='r', linewidth=2, linestyle='dashed')
axes[2].axvline(data.mode()[0], color='r', linewidth=2, linestyle='dotted')
axes[0].tick_params(axis='both', which='both', labelsize=10, labelbottom=True)
axes[1].tick_params(axis='both', which='both', labelsize=10, labelbottom=True)
axes[2].tick_params(axis='both', which='both', labelsize=10, labelbottom=True)
plott(df['Age'])
This is the resulting plot
Is there a way to add the legend in here in accordance to the 3 vertical lines
like this with each line type denoting the value?
Also, how to add more values in x axis of all three graphs?
like make it interval of 5 or 2 years apart?
Thanks
Give the axvlines a "label" value, then call plt.legend after plotting it.
Example:
import matplotlib.pyplot as plt
plt.plot([1,2,3],[1,2,3],label="Test")
plt.axvline(x=0.22058956, label="Test2", color="red")
plt.legend()
Output:

How to create a single legend for subplots [duplicate]

This question already has answers here:
How do I make a single legend for many subplots?
(10 answers)
Closed 6 months ago.
I am trying to replicate the following plot but with a different set of data:
My current plot has everything you see except the legend in the top right corner. I am having a hard time figuring out how I am supposed to add this in with my current code:
fig = plt.figure()
plt.subplot(3, 1, 1)
plt.title('Task Switches and Avg Task Switches by Timestep', fontsize=10)
plt.ylabel('Task Switches', fontsize=9)
plt.xlim(-35, timestep_num + 35)
plt.xticks(np.arange(0, timestep_num+1, 50), fontsize=-1, color='white')
plt.yticks(np.arange(0, 61, 20), fontsize=6)
plt.plot([stepsum_list[i][6] for i in range(len(stepsum_list))], color='royalblue',
linewidth=0.7, linestyle='', marker='.', markersize=1)
plt.plot([stepsum_list[i][6]/(i+1) for i in range(len(stepsum_list))], color='limegreen',
linewidth=0.6,)
plt.subplot(3, 1, 2)
plt.title('Task Demand per Timestep by Task', fontsize=10)
plt.ylabel('Task Demand', fontsize=9)
plt.xlim(-35, timestep_num + 35)
plt.xticks(np.arange(0, timestep_num+1, 50), fontsize=-1, color='white')
plt.yticks(np.arange(0, 6, 1), fontsize=6)
plt.plot([stepdem_list[i][1] for i in range(len(stepdem_list))], color='darkorange',
linewidth=0.7, linestyle='', marker='.', markersize=1)
plt.plot([stepdem_list[i][2] for i in range(len(stepdem_list))], color='yellowgreen',
linewidth=0.7, linestyle='', marker='.', markersize=1)
plt.plot([stepdem_list[i][3] for i in range(len(stepdem_list))], color='purple',
linewidth=0.7, linestyle='', marker='.', markersize=1)
plt.plot([stepdem_list[i][4] for i in range(len(stepdem_list))], color='blue', linewidth=0.7,
linestyle='', marker='.', markersize=1)
plt.subplot(3, 1, 3)
plt.title('Target and Tracker Movement',fontsize=10)
plt.ylabel('Movement', fontsize=9)
plt.xlabel('Timesteps', fontsize=9)
plt.xlim(-35, timestep_num + 35)
plt.xticks(np.arange(0, timestep_num+1, 50), fontsize=8)
plt.yticks(np.arange(-10, 11, 10), fontsize=6)
plt.plot([stepsum_list[i][4] for i in range(len(stepsum_list))], color='blue', linewidth=.5)
plt.plot([stepsum_list[i][2] for i in range(len(stepsum_list))], color='red', linewidth=.5)
fig.align_labels()
plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.4, hspace=0.4)
plt.savefig('prog02_output.png')
plt.show
I apologize for all of the repetitive code, I'm brand new to Python and this is my first time making a plot so I don't know all of the tricks just yet. I have found the function figlegend(), but I'm confused if this is what I am going to want to use, and if so how the parameters are working. Placing the legend in the correct spot (aligned with the top subplot) is also something I am trying to do, but can't seem to figure out.
I'm not asking anyone to write any code or rewrite what I have. Just for someone to point me in the right direction, whether that be explaining a function and what parameters it can take, or what might need to be changed in my current code to use figlegend().
The way I plot legends with my plots in Matplotlib is via the Axes.legend() function, shown below:
The source code is
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([0,1,2],[2,1,0], c='r', label='Plot 1')
ax.plot([0,1,2],[0,1,2], c='b', label='Plot 2')
ax.legend()
plt.show()
After you add labels to each of the data traces in your plot via the label keyword argument, then you can add a legend to the figure with
plt.gca().legend()
If your try to put more 3 variables, you can do this:
lns1 = plt.plot(x,y)
lns2 = plt.plot(x2,y)
lns3 = plt.plot(x3,y)
lns = lns1+lns2+lns3+lns4
labs = [l.get_label() for l in lns]
plt.figure()
When you go to plot, use this:
ax.legend(lns,labs,loc='lower center')

X-axis minor gridlines still not showing even after trying all solutions

My x-axis minor gridlines are not showing, this is my code
ax = plt.gca()
ax.minorticks_on()
plt.semilogx(data_x1,data_y1,"red")
plt.semilogx(data_x2,data_y2,"blue")
ax.grid(b=True, which='major',axis="both", color='k', linestyle='-', linewidth=0.5)
ax.grid(b=True, which='minor',axis="both", color='k', linestyle='-', linewidth=0.2)
plt.xlabel("frequency(Hz)")
plt.ylabel("Iramp(dB)")
plt.show()
enter image description here
Either I'm not sure of what you want, or your code is actually working correctly. The minor grid lines are those between the powers of 10. I made a little example to show a comparison of your plot with the minor grid lines on and off.
import numpy as np
import matplotlib.pyplot as plt
data_x1 = np.linspace(0,2,10)
data_x2 = np.linspace(0,4,10)
data_y1 = np.random.rand(10)
data_y2 = np.random.rand(10)
fig, axall =plt.subplots(1,2, figsize=(10,5))
# your code with some changes
ax = axall[0]
ax.minorticks_on()
ax.semilogx(data_x1,data_y1,"red")
ax.semilogx(data_x2,data_y2,"blue")
ax.grid(b=True, which='major',axis="both", color='k', linestyle='-', linewidth=0.5)
ax.grid(b=True, which='minor',axis="both", color='k', linestyle='-', linewidth=0.2)
ax.set_xlabel("frequency(Hz)")
ax.set_ylabel("Iramp(dB)")
# code to make the plot on the right.
ax = axall[1]
ax.minorticks_on()
ax.semilogx(data_x1,data_y1,"red")
ax.semilogx(data_x2,data_y2,"blue")
ax.grid(b=True, which='major',axis="both", color='k', linestyle='-', linewidth=0.5)
# ax.grid(b=True, which='minor',axis="both", color='k', linestyle='-', linewidth=0.2)
ax.set_xlabel("frequency(Hz)")
ax.set_ylabel("Iramp(dB)")
plt.show()
Note how I commented out your minor grid lines.

Subplot date formatting in Axis

I have a 2x2 graph with date in x-axis in both graphs. I have used datetime.strptime to bring a string into type = datetime.datetime object format.
However I am planning to have some 12 subplots and doing this the following way seems messy.
Is there a better 'pythonic' way?
This is what I have:
xx.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%y %H:%M'))
plt.grid(True)
plt.ylabel('paramA',fontsize=8, color = "blue")
plt.tick_params(axis='both', which='major', labelsize=8)
plt.plot(date_list, myarray[:,0], '-b', label='paramA')
plt.setp(plt.xticks()[1], rotation=30, ha='right') # ha is the same as horizontalalignment
xx = plt.subplot(2,1,2)
xx.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%y %H:%M'))
plt.grid(True)
plt.ylabel('paramB', 'amount of virtual mem',fontsize=8, color = "blue")
plt.tick_params(axis='both', which='major', labelsize=8)
plt.plot(date_list, myarray[:,1], '-y', label='paramB')plt.setp(plt.xticks()[1], rotation=30, ha='right') # ha is the same as horizontalalignment ```
PS: Initially I tried defining the plot as follows. This however did not work:
fig, axs = plt.subplots(2,1,figsize=(15,15))
plt.title('My graph')
for ax in enumerate(axs):
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%y %H:%M:%S'))
You failed to provide any data or a Minimal, Complete, and Verifiable example. Nevertheless, something like this should work. You can extend it to your real case by using desired number of rows and columns in the first command.
fig, axes = plt.subplots(nrows=2, ncols=3)
labels = ['paramA', 'paramB', 'paramC', 'paramD', 'paramE', 'paramF']
for i, ax in enumerate(axes.flatten()):
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%y %H:%M'))
ax.grid(True)
ax.set_ylabel(labels[i], fontsize=8, color="blue")
ax.tick_params(axis='both', which='major', labelsize=8)
ax.plot(date_list, myarray[:,i], '-b', label=labels[i])
plt.setp(plt.xticks()[1], rotation=30, ha='right') # ha is the same as horizontalalignment
EDIT:
Change your code to
fig, axs = plt.subplots(2,1,figsize=(15,15))
plt.title('My graph')
for ax in axs:
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%y %H:%M:%S'))

How to create a legend in matplotlib

I am working on a regression problem and I want to plot 3 DataFrames. I don't know how to set the labels for the Dataframes. I want blue->ACTUAL, green->SVR, red->MLR.
What is wrong with the code?
ax1 = y_test[1800:1900].plot(color='blue', linewidth=3)
predicted_y[1800:1900].plot(color='green', linewidth=3, ax =ax1)
predicted_y1[1800:1900].plot(color='red', linewidth=3, ax=ax1)
plt.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05), prop={'size':35})
plt.show()
I plot this and it shows me all colors with 0 values.
I think it should work if you add labels to your plots:
ax1 = y_test[1800:1900].plot(color='blue', linewidth=3, label = 'ACTUAL')
predicted_y[1800:1900].plot(color='green', linewidth=3, ax =ax1, label = 'SVR')
predicted_y1[1800:1900].plot(color='red', linewidth=3, ax=ax1, label = 'MVR')
plt.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05), prop={'size':35})
plt.show()

Categories

Resources