This question already has answers here:
How to force the Y axis to only use integers
(3 answers)
Closed 8 months ago.
I am making a bot which tracks discord server stats and makes a graph of them.
While making the bot, I faced a problem. The bot shows floating point numbers in the graph which are not supposed to be there.
Is it possible to disable the float numbers and show only 12, 13, 14 instead of 12, 12.25, 12.50, etc?
Answer
I suppose your data are in a y list. In this case you can use ax.set_yticks() as here:
yticks = range(min(y), max(y) + 1)
ax.set_yticks(yticks)
Code
import matplotlib.pyplot as plt
plt.style.use('dark_background')
x = ['14.09', '15.09', '16.09', '17.09', '18.09']
y = [12, 13, 13, 14, 14]
fig, ax = plt.subplots()
ax.plot(x, y, color = 'green', linestyle = '-', marker = 'o', markerfacecolor = 'red')
ax.set_facecolor('white')
ax.set_ylabel('Member count')
ax.set_title("Member count for 'СПГ'")
plt.setp(ax.xaxis.get_majorticklabels(), rotation = 90)
yticks = range(min(y), max(y) + 1)
ax.set_yticks(yticks)
plt.show()
Output
Related
This question already has answers here:
Plot a horizontal line on a given plot
(7 answers)
Closed 1 year ago.
I would like to draw a horizontal line with matplotlib's plt.axhline() function, but I want the horizontal line to stop at the absolute value of 5 on the x-axis. How do I set xmax in plt.axhline() to stop at 5?
plt.figure()
plt.plot(np.arange(-60, 60, 20), np.arange(0, 1.2, 0.2))
plt.axhline(y = 0.5, xmax = 5, c= 'r')
You need to use plt.hlines instead, also specify a xmin and change c to color .
import matplotlib.pyplot as plt
import numpy as np
xmin = -65
plt.figure()
plt.plot(np.arange(-60, 60, 20), np.arange(0, 1.2, 0.2))
plt.hlines(y = 0.5, xmin=xmin , xmax = 5, color= 'r')
plt.xlim(left=xmin);
This question already has answers here:
How to draw vertical lines on a given plot
(6 answers)
Closed 1 year ago.
I'm using the following:
fig, ax = plt.subplots(figsize=(20, 10))
ax.set_ylim(bottom=0, top=10)
for i in range(4):
ax.axvline(x=i, ymin=5, ymax=9, color="red", linewidth=40)
Which gives:
I would expect there to be a vertical line at each point from y = 5 to y = 9.
You should use matplotlib.pyplot.vlines, as suggested by BigBen in the comment:
for i in range(4):
ax.vlines(x=i, ymin=5, ymax=9, color="red", linewidth=40)
If you look at the parameters for axvline, you see that ymin and ymax goes from 0 to 1. A fraction of your complete ylimit.
https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.axvline.html
So you need something like .5 to .9 or calculate the appropriate fractions.
fig, ax = plt.subplots(figsize=(20, 10))
ax.set_ylim(bottom=0, top=10)
for i in range(4):
ax.axvline(x=i, ymin=.5, ymax=.9, color="red", linewidth=40)
Output:
This question already has answers here:
Create a stacked bar plot and annotate with count and percent
(2 answers)
Closed 5 months ago.
I am trying to get the percentage labels on top of the stacked bars, but I can't figure it out.
fig, ax = plt.subplots(figsize=(24, 8))
minor_treatment_choice.plot(
x = 'surgeon_id',
kind = 'bar',
stacked = True, ax=ax)
df_total = (minor_treatment_choice['X'] + minor_treatment_choice['Y'])
df_rel = minor_treatment_choice[minor_treatment_choice.columns[2:]].div(df_total, 0.)*100.
for n in df_rel:
for i, (cs, ab, pc) in enumerate(zip(minor_treatment_choice.iloc[:, 2:].cumsum(1)[n], minor_treatment_choice[n], df_rel[n])):
plt.text(cs - ab / 2, i, str(np.round(pc, 1)) + '%', va = 'center', ha = 'center', fontsize = 10)
plt.xticks(fontsize=15,rotation=30)
plt.yticks(fontsize=15)
ax.set_xlabel ('Surgeon IDs',fontsize=15)
ax.set_ylabel ('Minor Severity Cases',fontsize=15)
fig.suptitle('Treatments X & Y for Minor Cases',fontsize=20)
ax.legend(title='Treatments')
plt.show()
Can anyone help?
Using data from the official website, I created an example of percentage annotation. ax.text(x,y,text) is the basic idea. Looking at the current output, it looks like the x-axis is not taken correctly.
import matplotlib.pyplot as plt
import pandas as pd
speed = [0.1, 17.5, 40, 48, 52, 69, 88]
lifespan = [2, 8, 70, 1.5, 25, 12, 28]
index = ['snail', 'pig', 'elephant', 'rabbit', 'giraffe', 'coyote', 'horse']
df = pd.DataFrame({'speed': speed,'lifespan': lifespan}, index=index)
fig, ax = plt.subplots(figsize=(24, 8))
df.plot.bar(stacked=True, ax=ax)
per = df['speed'] / df['speed'].sum()
for i,p in enumerate(per):
ax.text(i, df.speed[i], '{:.2}%'.format(p), va='center', ha='center', fontsize=14)
ax.set_xticklabels(df.index, fontsize=15, rotation=30)
plt.setp(ax.get_xticklabels(), fontsize=15)
ax.set_xlabel ('Surgeon IDs', fontsize=15)
ax.set_ylabel ('Minor Severity Cases', fontsize=15)
ax.set_title('Treatments X & Y for Minor Cases', fontsize=20)
ax.legend(title='Treatments')
plt.show()
I have a question concerning matplotblib in Python. I am working with a dataset, which has 30 sessions. In each session there are 0 to 5 runs. I have created a plot, which displays the values of each run over the run. So the runs go from 0-200. However, I need the ticks to be resetted when a new run starts. So instead of 0-200, I want 0,1,2,3...0,1,2...0,1,2,3,4,5. The graph as it is however, is not supposed to change. Do you have any idea how this would be possible?
The code:
for ses in range(len(all_runs)):
if len(all_runs[ses]) > 0:
plt.plot(xval[ses],all_runs[ses],'.-',color='tab:blue')
You can pass a labels argument to plt.xticks(), specifying the repeating tick labels, without changing the plotted data. For example:
import matplotlib.pyplot as plt
n = 5 # number of ticks per run
r = 3 # number of runs
# sample plot
plt.plot(list(range(n * r)))
plt.xticks(list(range(n * r)))
# set repeating tick labels
ticks = list(plt.xticks()[0])
plt.xticks(ticks, labels = ticks[:n] * r);
If I understand the question correctly, this is how it would work. Optionally, the minor ticks could indicate the sessions.
import matplotlib.pyplot as plt
import numpy as np
xval = [np.array([0, 1, 2, 3, 4]), np.array([5, 6, 7, 8, 9, 10]), np.array([11, 12, 13, 14, 15, 16, 17])]
all_runs = [np.random.randint(1, 10, len(xv)) for xv in xval]
total_len = sum([len(xv) for xv in xval])
for ses in range(len(all_runs)):
if len(all_runs[ses]) > 0:
plt.plot(xval[ses], all_runs[ses], '.-', color='tab:blue')
# if ses > 0:
# plt.axvline(xval[ses][0] - 0.5, ls=':', lw=1, color='purple')
plt.xticks(range(total_len), [i for xv in xval for i in range(len(xv))])
ax = plt.gca()
ax.set_xticks([xv[0] + 0.1 for xv in xval if len(xv) > 0], minor=True)
ax.set_xticklabels([f'session {i}' for i, xv in enumerate(xval) if len(xv) > 0], minor=True)
ax.tick_params(axis='x', which='minor', length=0, pad=18)
for tick in ax.xaxis.get_minor_ticks():
tick.label1.set_horizontalalignment('left')
plt.show()
This question already has answers here:
How to specify different color for a specific year value range in a single figure? (Python)
(2 answers)
Closed 4 years ago.
Say I have three sets of data x, y and z.
I want to plot a scatter of x and y, but I want to assign colours to different points depending on what their corresponding z values are.
So for example for every point where z is in the range 0 to 1 I want the data points to be red, and when z in the range 1 to 3 I want the points to be blue etc.
How do I do this?
Try this. adopted from ImportanceOfBeingErnest answer here
import matplotlib.pyplot as plt
import matplotlib.colors
import numpy as np
x = np.linspace(0, 10, 100)
y = np.random.randint(0, 50, size=100)
z = np.random.rand(100)*10
bounds = [0,1,3,10]
colors = ["r", "b", "g"]
plt.figure(figsize=(8,6))
cmap = matplotlib.colors.ListedColormap(colors)
norm = matplotlib.colors.BoundaryNorm(bounds, len(colors))
rect = plt.scatter(x, y, s = 100, c=z, cmap=cmap, norm=norm)
cbar = plt.colorbar(rect, spacing="proportional")
cbar.set_label('Color', rotation=270, labelpad=10)
for i, txt in enumerate(z):
plt.annotate(np.around(txt, 1), (x[i], y[i]))
plt.show()