Python Matplotlib - Show Tick Marks associated to Plotted Points - python

how can I show the label of the value of each point I'm plotting on the y axis?
I am currently plotting like this:
d=[2,5,10,20,30,40,50,70,100,200]
t0=[0.04,0.08,0.15,0.4,0.6,0.8,1.0,1.4,2.1,5.5]
fig, ax = plt.subplots()
plt.plot(d,t0,marker='o')
xmajorLocator = MultipleLocator(10)
xmajorFormatter = FormatStrFormatter('%d')
xminorLocator = MultipleLocator(1)
ymajorLocator = MultipleLocator(0.5)
ymajorFormatter = FormatStrFormatter('%.2f')
yminorLocator = MultipleLocator(0.05)
ax.xaxis.set_major_locator(xmajorLocator)
ax.xaxis.set_major_formatter(xmajorFormatter)
ax.xaxis.set_minor_locator(xminorLocator)
ax.yaxis.set_major_locator(ymajorLocator)
ax.yaxis.set_major_formatter(ymajorFormatter)
ax.yaxis.set_minor_locator(yminorLocator)
xlim([0,250])
show()
I just want the values of the t0 list to be marked and appear on the y axis, while keeping the current marks and ticks format.

import matplotlib.pyplot as plt
d=[2,5,10,20,30,40,50,70,100,200]
t0=[0.04,0.08,0.15,0.4,0.6,0.8,1.0,1.4,2.1,5.5]
fig, ax = plt.subplots()
plt.plot(d,t0,marker='o')
ax.set_xticks(d)
ax.set_yticks(t0)
plt.show()

Related

Matplotlib two X axis position switching

I would like to make a plot having two X-axis.
But I would like to set the host x axis to top and the other x axis to bottom.
I tried:
axs[i].barh(bins[:len(count_vol)], count_vol, align='edge', color='black', height = 10) # horizontal bar plot
axs[i].set_xlabel('concentration (n/m3)')
axs[i].set_ylabel('depth (m)')
axs[i].invert_yaxis()
axs[i].set_title(org, y =1.0) # subplot title
axs[i].xaxis.set_major_formatter(FormatStrFormatter('%.2f'))
axs[i].xaxis.tick_top() # x axis to top of the subplot
#plt.show()
# add environmental data
temp_ax = axs[i].twiny()
temp_ax.plot(temperature, depth, color='red')
temp_ax.set_xlabel('temperature', color='red')
temp_ax.xaxis.tick_bottom() x axis to botton of the subplot
When I activatd 'plt.show()' the host x axis was on the top which I wanted to plot.
But after I ran whole script above, both x axis are on the bottom.
What is the problem with my code?
There are various ways to add an extra xaxis on top.
ticks and labels are with the wrong position
I guess temp_ax.xaxis.tick_bottom() is rebundant.
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
fig, axs = plt.subplots(1, 3)
# secondary axis
axs[0].plot(x)
axs[0].set_xlabel('label bottom')
secax = axs[0].secondary_xaxis('top')
secax.set_xlabel('label top')
# twiny()
axs[1].set_xlabel('label bottom')
twax = axs[1].twiny()
twax.set_xlabel('label top')
# handle properties
axs[2].xaxis.tick_top()
axs[2].xaxis.set_label_position('top')
axs[2].set_xlabel('label top')
plt.show()

Show only exact values of data point on axes with matplotlib figure

I want to show only exact values (x, y) on axes or coordinates of data point by matplotlib. My work below that
def plot_sample_individual(id = None):
if id is None:
id = random.randint(0, len(ca_the))
fig, ax = plt.subplots(1, 1, figsize=(5, 5))
ax.plot(week[:7], ca_the[id, :],'--ro')
ax.set_title('ID cá thể '+ str(ID[id, 0]))
ax.set_ylabel('Sản lượng trứng trung bình tuần')
ax.set_xlabel('Tuần')
and result of code is:
How to show only 3 values on axes y and 5 values in axes x ?
Use the x and y data to set the Axes ticks:
from matplotlib import pyplot as plt
x = [24,25,26,27,28]
y = [7,4,5,4,4]
fig,ax = plt.subplots()
ax.plot(x,y)
ax.set_xticks(x)
ax.set_yticks(y)
plt.show()
plt.close()
Ticks and tick labels

Create Subplots in For Loop Matplotlib

i'm trying to make a 3,2 subplot using matplotlib and I'm not understanding how to do this after reading the documentation as it applies to my code as follows:
import pandas as pd
from sys import exit
import numpy as np
import matplotlib.pyplot as plt
import datetime
import xarray as xr
import cartopy.crs as ccrs
import calendar
list = [0,1,2,3,4,5]
now = datetime.datetime.now()
currm = now.month
import calendar
fig, axes = plt.subplots(nrows=3,ncols=2)
fig.subplots_adjust(hspace=0.5)
fig.suptitle('Teleconnection Pos+ Phases {} 2020'.format(calendar.month_name[currm-1]))
#for x in list:
#for ax, x in zip(axs.ravel(), list):
for x, ax in enumerate(axes.flatten()):
dam = DS.where(DS['time.year']==rmax.iloc[x,1]).groupby('time.month').mean()#iterate by index
of column "1" or the years
dam = dam.sel(month=3)#current month mean 500
dam = dam.sel(level=500)
damc = dam.to_array()
lats = damc['lat'].data
lons = damc['lon'].data
#plot data
ax = plt.axes(projection=ccrs.PlateCarree())
ax.coastlines(lw=1)
damc = damc.squeeze()
ax.contour(lons,lats,damc,cmap='jet')
ax.set_title(tindices[x])
plt.show()
#plt.clf()
I've tried multiple options some of which are above in the comments and I cannot get the subplots to show in the 3,2 subplot i'm expecting. I only get single plots. I've included the first plot in the for loop below as you can see it's not plotted inside the 3,2 subplot region:
[![enter image description here][1]][1]
The row with "ax.contour" may be the problem but i'm not sure. Thank you very much and here below is my target subplot region:
[![enter image description here][1]][1]
Without a reproducible sample data, below cannot be tested. However, your loop assigns a new ax and does not use the ax being iterating on. Additionally, plt.show() is placed within the loop. Consider below adjustment
for x, ax in enumerate(axes.flatten()):
...
ax = plt.axes(projection=ccrs.PlateCarree())
...
plt.show()
Consider placing projection in the plt.subplots and then index axes within loop:
fig, axes = plt.subplots(nrows=3, ncols=2, subplot_kw={'projection': ccrs.PlateCarree()})
fig.subplots_adjust(hspace=0.5)
fig.suptitle('Teleconnection Pos+ Phases {} 2020'.format(calendar.month_name[currm-1]))
axes = axes.flatten()
for x, ax in enumerate(axes):
dam = DS.where(DS['time.year']==rmax.iloc[x,1]).groupby('time.month').mean()
dam = dam.sel(month=3)#current month mean 500
dam = dam.sel(level=500)
damc = dam.to_array()
lats = damc['lat'].data
lons = damc['lon'].data
axes[x].coastlines(lw=1)
damc = damc.squeeze()
axes[x].contour(lons, lats, damc, cmap='jet')
axes[x].set_title(tindices[x])
plt.show()
plt.clf()

Labeling first and last data point in matplotlib 3D

I have plotted a set of data points in a 3D figure and I would like to label the first and last data point with a different color and label them by a legend. How do I do that?
The code I have used is
from mpl_toolkits.mplot3d import Axes3D
x = np.array([0,1,2,3])
y = np.array([0,1,2,3])
z = np.array([0,1,2,3])
fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')
ax.plot(x,y,z,'o-',markersize=5)
plt.show()
You can redraw the first and last point on the plot and label them as you give them color.
from mpl_toolkits.mplot3d import Axes3D
x = np.array([0,1,2,3])
y = np.array([0,1,2,3])
z = np.array([0,1,2,3])
fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')
ax.plot(x[:1], y[:1], z[:1], 'o-',c='green', label="first", zorder=2)
ax.plot(x[-1:], y[-1:], z[-1:], 'o-',c='coral', label="last", zorder=2)
ax.plot(x,y,z,'o-',markersize=5, zorder=1)
ax.legend()
plt.show()
Output:

How to avoid negative numbers on axis in matplotlib scatterplot

I am doing a simple scatterplot using Pythons scatterplot. But no matter how I set my axis, and no matter that I don't have any negative values I get negative values at the x-axis. How do I force the axis to start at 0?
My code:
fig, ax = plt.subplots(1)
ax.scatter(lengths,breadths, alpha=0.3, color="#e74c3c", edgecolors='none')
spines_to_remove = ['top', 'right']
for spine in spines_to_remove:
ax.spines[spine].set_visible(False)
ax.xaxis.set_ticks_position('none')
ax.yaxis.set_ticks_position('none')
ax.xaxis.set_view_interval(0,400)
ax.yaxis.set_view_interval(0,90)
figname = 'scatterlengthsbreadths.pdf'
fig.savefig(figname, bbox_inches='tight')
You can use ax.set_xlim(lower_limit, upper_limit) to choose your x-limits. Note that there is a similar command ax.set_ylim for the y-limits.
Note that if you're just using the pyplot interface, i.e. without using fig and ax, then the command is plt.xlim().
For example:
import matplotlib.pyplot as plt
x = [1,2,3]
y = [4,5,6]
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xlim(0, 10)
plt.show()

Categories

Resources