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

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

Related

Continuous color scale and nice range with pyplor LogLocator

I am trying to get a continuous color scale in matplotlib for a log plot. But I also want to preserve the nice tick structure and upper and lower limits in the colorbar.
I can only figure out how to do one or the other.
Here the code that generates the two versions
import matplotlib.ticker as ticker
import numpy as np
x = np.linspace(1,200, 50)
y = np.linspace(1,300, 50)
z = np.outer(y, x)
bounds = [np.amin(z), np.amax(z)]
bounds = np.log10(bounds)
bounds[0] = np.floor(bounds[0])
bounds[1] = np.ceil(bounds[1])
bounds = np.power(10, bounds)
fig, ax = plt.subplots()
tickLocator = ticker.LogLocator()
CS = ax.contourf(x, y, z, locator=tickLocator)
ax.set_title("Not enough color bar levels")
cbar = plt.colorbar(CS)
fig, ax = plt.subplots()
tickLocator = ticker.LogLocator(subs=range(1, 10))
CS = ax.contourf(x, y, z, locator=tickLocator)
ax.set_title("Labels missing and not enough range in color bar")
cbar = plt.colorbar(CS)
print("Boundary values")
print(bounds)
print("Tick values")
print(cbar.get_ticks())
plt.show()
With the first version I get nice end points for the ticks, but the levels are very coarse.
With the second version most of the tick labels are missing and the highest tick is smaller than the biggest value in the array.
I found something that works for me by using pcolormesh instead of contourf.
Here the code and output for anyone with a similar problem
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np
x = np.linspace(1,200, 200)
y = np.linspace(1,300, 200)
z = np.outer(y, x)
bounds = [np.amin(z), np.amax(z)]
bounds = np.log10(bounds)
bounds[0] = np.floor(bounds[0])
bounds[1] = np.ceil(bounds[1])
bounds = np.power(10, bounds)
fig, ax = plt.subplots()
CS = ax.pcolormesh(x, y, z, norm=colors.LogNorm(*bounds), shading="auto")
cbar = plt.colorbar(CS, ax=ax)
print("Boundary values")
print(bounds)
print("Tick values")
print(cbar.get_ticks())
plt.show()

Seaborn plot with second y axis

i wanted to know how to make a plot with two y-axis so that my plot that looks like this :
to something more like this by adding another y-axis :
i'm only using this line of code from my plot in order to get the top 10 EngineVersions from my data frame :
sns.countplot(x='EngineVersion', data=train, order=train.EngineVersion.value_counts().iloc[:10].index);
I think you are looking for something like:
import matplotlib.pyplot as plt
x = [1,2,3,4,5]
y = [1000,2000,500,8000,3000]
y1 = [1050,3000,2000,4000,6000]
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.bar(x, y)
ax2.plot(x, y1, 'o-', color="red" )
ax1.set_xlabel('X data')
ax1.set_ylabel('Counts', color='g')
ax2.set_ylabel('Detection Rates', color='b')
plt.show()
Output:
#gdubs If you want to do this with Seaborn's library, this code set up worked for me. Instead of setting the ax assignment "outside" of the plot function in matplotlib, you do it "inside" of the plot function in Seaborn, where ax is the variable that stores the plot.
import seaborn as sns # Calls in seaborn
# These lines generate the data to be plotted
x = [1,2,3,4,5]
y = [1000,2000,500,8000,3000]
y1 = [1050,3000,2000,4000,6000]
fig, ax1 = plt.subplots() # initializes figure and plots
ax2 = ax1.twinx() # applies twinx to ax2, which is the second y axis.
sns.barplot(x = x, y = y, ax = ax1, color = 'blue') # plots the first set of data, and sets it to ax1.
sns.lineplot(x = x, y = y1, marker = 'o', color = 'red', ax = ax2) # plots the second set, and sets to ax2.
# these lines add the annotations for the plot.
ax1.set_xlabel('X data')
ax1.set_ylabel('Counts', color='g')
ax2.set_ylabel('Detection Rates', color='b')
plt.show(); # shows the plot.
Output:
Seaborn output example
You could try this code to obtain a very similar image to what you originally wanted.
import seaborn as sb
from matplotlib.lines import Line2D
from matplotlib.patches import Rectangle
x = ['1.1','1.2','1.2.1','2.0','2.1(beta)']
y = [1000,2000,500,8000,3000]
y1 = [3,4,1,8,5]
g = sb.barplot(x=x, y=y, color='blue')
g2 = sb.lineplot(x=range(len(x)), y=y1, color='orange', marker='o', ax=g.axes.twinx())
g.set_xticklabels(g.get_xticklabels(), rotation=-30)
g.set_xlabel('EngineVersion')
g.set_ylabel('Counts')
g2.set_ylabel('Detections rate')
g.legend(handles=[Rectangle((0,0), 0, 0, color='blue', label='Nontouch device counts'), Line2D([], [], marker='o', color='orange', label='Detections rate for nontouch devices')], loc=(1.1,0.8))

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:

python/matplotlib/seaborn- boxplot on an x axis with data points

My data set is like this: a python list with 6 numbers [23948.30, 23946.20, 23961.20, 23971.70, 23956.30, 23987.30]
I want them to be be a horizontal box plot above an x axis with[23855 and 24472] as the limit of the x axis (with no y axis).
The x axis will also contain points in the data.
(so the box plot and x axis have the same scale)
I also want the box plot show the mean number in picture.
Now I can only get the horizontal box plot.
(And I also want the x-axis show the whole number instead of xx+2.394e)
Here is my code now:
`
def box_plot(circ_list, wear_limit):
print circ_list
print wear_limit
fig1 = plt.figure()
plt.boxplot(circ_list, 0, 'rs', 0)
plt.show()
`
Seaborn code I am trying right now:
def box_plot(circ_list, wear_limit):
print circ_list
print wear_limit
#fig1 = plt.figure()
#plt.boxplot(circ_list, 0, 'rs', 0)
#plt.show()
fig2 = plt.figure()
sns.set(style="ticks")
x = circ_list
y = []
for i in range(0, len(circ_list)):
y.append(0)
f, (ax_box, ax_line) = plt.subplots(2, sharex=True,
gridspec_kw={"height_ratios": (.15, .85)})
sns.boxplot(x, ax=ax_box)
sns.pointplot(x, ax=ax_line, ay=y)
ax_box.set(yticks=[])
ax_line.set(yticks=[])
sns.despine(ax=ax_line)
sns.despine(ax=ax_box, left=True)
cur_axes = plt.gca()
cur_axes.axes.get_yaxis().set_visible(False)
sns.plt.show()
I answered this question in the other post as well, but I will paste it here just in case. I also added something that I feel might be closer to what you are looking to achieve.
l = [23948.30, 23946.20, 23961.20, 23971.70, 23956.30, 23987.30]
def box_plot(circ_list):
fig, ax = plt.subplots()
plt.boxplot(circ_list, 0, 'rs', 0, showmeans=True)
plt.ylim((0.28, 1.5))
ax.set_yticks([])
labels = ["{}".format(int(i)) for i in ax.get_xticks()]
ax.set_xticklabels(labels)
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['left'].set_color('none')
ax.spines['bottom'].set_position('center')
ax.spines['bottom'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
plt.show()
box_plot(l)
The result:
Do let me know if it correspond to what you were looking for.

Python Matplotlib - Show Tick Marks associated to Plotted Points

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()

Categories

Resources