matplotlib - change number display and remove the mini lines [duplicate] - python

This question already has answers here:
Prevent scientific notation
(1 answer)
Python hide ticks but show tick labels
(9 answers)
How to format axis number format to thousands with a comma
(10 answers)
Closed last month.
I would like to have two changes:
Instead of 1.2 I want to have 1.200.000 (also for the others) as x axis tick labels - red colour
Get rid of the mini-lines (y axis ticks) - blue colour
Here is my code:
import pandas as pd
#import numpy as np
import matplotlib.pyplot as plt
df = pd.read_excel(r"C:\Users\...\3_Python.xlsx", sheet_name=2)
a = [_*200000 for _ in range(12)]
b = [_*200000 for _ in range(12)]
df.plot(kind="scatter"
,color="dimgrey"
,marker="D"
,y="Vorher"
,x="Nachher"
,title="Title"
,xticks=[_*200000 for _ in range(12)]
,yticks=[_*200000 for _ in range(12)]
)
plt.plot(a, b, label="xxx", linestyle="-", color="black")
plt.text(1000000, 1, "xxxx")
plt.text(1, 1000000, "yyyyy")
plt.ylim(ymin=0, ymax=1200000)
plt.xlim(xmin=0, xmax=1200000)
plt.xlabel("past")
plt.ylabel("future")
plt.grid(True, linewidth=2, color="grey")
plt.show()

Related

Plotting dataframe using matplot lib [duplicate]

This question already has answers here:
Line plot with data points in pandas
(2 answers)
Closed 1 year ago.
Hi I am trying to get a line plot for a dataframe:
i = [0.01,0.02,0.03,....,0.98,0.99,1.00]
values= [76,98,22,.....,32,98,100]
but there is index from 0,1,...99 as well and when I plot the index line also gets plotted. How do I ignore the plotting of index? I used the following code:
plt.plot(df,color= 'blue', label= 'values')
plt.title('values for corresponding i')
plt.legend(loc= 'upper right')
plt.xlabel("i")
plt.ylabel("values")
plt.show()
You could use plot.line directly on pandas dataframe, it's a wrapper around matplotlib and it makes stuff easier.
Example:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Generate random DataFrame
i = np.arange(0, 1, 0.01)
values = np.random.randint(1, 100, 100)
df = pd.DataFrame({"i": i, "values": values})
# Plot
df.plot.line(x="i", y="values", color="blue", label="values")
plt.title("values for corresponding i")
plt.legend(loc="upper right")
plt.xlabel("i")
plt.ylabel("values")
Result:

Adding y values to a plot using matplotlib [duplicate]

This question already has answers here:
How to plot and annotate a grouped bar chart
(1 answer)
Python matplotlib multiple bars
(7 answers)
How to annotate grouped bar plot with percent by hue/legend group
(1 answer)
How to plot grouped bars in the correct order
(1 answer)
How to get a grouped bar plot of categorical data
(1 answer)
Closed 1 year ago.
I would like to add the y values to my plot for each year to make the graph easily readable but not sure how to do it. I have tried using the enumerate function but it does not return the desired output. Any guidance on this would be helpful.
import numpy as np
import pandas as pd
from matplotlib import pyplot
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
laikipia = pd.DataFrame({
"2020":[5.21, 20.91, 17.05],
"2021":[20.91, 19.91, 19.76],
},
index=["Cropland", "Forestland", "Shrubland"]
)
c = ['#FFDB5C', '#358221', '#EECFA8']
laikipia.plot(kind="bar", color=c)
plt.title("")
plt.xlabel("Laikipia LULC")
plt.ylabel("Area Loss (ha)")
plt.legend(laikipia, bbox_to_anchor=(1, 1))
plt.xticks(rotation=0)
#plt.yticks(round [plotdata], 0)
x = laikipia
y = [70, 60, 50, 40, 30, 20, 10, 0]
max_y_lim = max(y)
min_y_lim = min(y)
plt.ylim(min_y_lim, max_y_lim)
for i, v in enumerate(y):
plt.text(0, i, y[i], str(v), ha="center", va = "bottom")
plt.show()
plt.tight_layout()
plot output

Matplotlib bar chart for negative numbers going above x-axis [duplicate]

This question already has answers here:
Modify tick label text
(13 answers)
Closed 4 years ago.
I am trying to make a bar chart of negative values where the baseline x-axis is at -10 instead of 0 and the values, because they are all -10<x<0, extend up from the baseline.
If I plot it as is, the bars extend downward:
import matplotlib.pyplot as plt
vals = [-4, -6, -8, -6, -5]
plt.bar(range(len(vals)), vals)
I could fake it in some sense by adding 10 to the data, but then I would have to remove the y-tick values, and I need to keep them.
new_vals = [val + 10 for val in vals]
plt.yticks([])
plt.bar(range(len(new_vals)), new_vals)
So how can I make the second image with the y-ticks of the first image and, preferably, without "faking" any of the data?
Following https://matplotlib.org/gallery/ticks_and_spines/custom_ticker1.html example, you can also do like this:
from matplotlib.ticker import FuncFormatter
def neg_tick(x, pos):
return '%.1f' % (-x if x else 0) # avoid negative zero (-0.0) labels
formatter = FuncFormatter(neg_tick)
fig, ax = plt.subplots()
ax.yaxis.set_major_formatter(formatter)
plt.bar(range(len(vals)), [-v for v in vals]) # or -numpy.asarray(vals)
# or, let Python enumerate bars:
# plt.bar(*zip(*enumerate(-v for v in vals)))
plt.show()
You cannot not "fake" data. Bar charts plot bars up for positive data and down for negative. If you want things differently, you need to trick bar chart somehow.
IMO, the above solution is better than https://stackoverflow.com/a/11250884/8033585 because it does not need the trick with drawing canvas, changing labels, etc.
If you do want to have "reverted" bar length (as it is in your example), then you can do the following:
from matplotlib.ticker import FuncFormatter
import numpy as np
# shifted up:
vals = np.asarray(vals)
minval = np.amin(vals)
minval += np.sign(minval) # "add" 1 so that "lowest" bar is still drawn
def neg_tick(x, pos):
return '%.1f' % (x + minval if x != minval else 0)
formatter = FuncFormatter(neg_tick)
fig, ax = plt.subplots()
ax.yaxis.set_major_formatter(formatter)
plt.bar(*zip(*enumerate(-minval + vals)))
plt.show()
Try matplotlib.axes.Axes.invert_yaxis
from matplotlib import pyplot as plt
vals = [-4, -6, -8, -6, -5]
plt.bar(range(len(vals)), vals)
fig, ax1 = plt.subplots(1,1)
ax1.bar(range(len(vals)), vals)
ax1.invert_yaxis()

How to adjust space between Matplotlib/Seaborn subplots for multi-plot layouts [duplicate]

This question already has answers here:
Improve subplot size/spacing with many subplots
(8 answers)
Closed 5 months ago.
The following figure shows the standard Seaborn/Matplotlib Boxplots in a 2 X 2 grid layout:
It is pretty much what I want except that I would like to put some more space between the first row of the of the plots and the second row. The distance between the X-axis labels of the first row plots and the title of the second row plots is almost non-existent. I have been playing with the parameters as explained in this thread:
StackOverflow Thread
Here is my relevant code:
import math
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from PyPDF2 import PdfFileMerger
import seaborn as sns
num_cols = 2
num_rows = int(math.ceil(tot_plots / float(num_cols)))
fig, axes = plt.subplots(nrows=num_rows, ncols=num_cols, figsize=(16, 16))
x_var = df_orig['hra']
for idx, ax in enumerate(axes.flat):
data_var = current_cols[idx]
y_var = df_orig[data_var]
title_str = ''
sns.boxplot(x=x_var, y=y_var, ax=ax,
order=order, palette=color, showfliers=False)
ax.set_title(data_var + title_str)
ax.xaxis.label.set_visible(False)
ax.yaxis.label.set_visible(False)
ax.xaxis.set_tick_params(labelsize=8)
ax.yaxis.set_tick_params(labelsize=8)
plt.setp(ax.xaxis.get_majorticklabels(), rotation=90)
fig.suptitle("Sampling BoxPlots", x=0.5, y=0.93, fontsize=14, fontweight="bold")
plt.tight_layout()
plt.subplots_adjust(top=0.8)
pdf_pages = PdfPages(file_name)
pdf_pages.savefig()
pdf_pages.close()
Have you tried adjusting hspace = 0.8 instead? According to matplotlib's reference that's the argument for changing the height between subplots, and not top.
plt.subplots_adjust(hspace = 0.8)

How can I rotate the auto-generated x-axis labels of a matplotlib plot? [duplicate]

This question already has answers here:
Date ticks and rotation in matplotlib
(6 answers)
Closed 7 years ago.
I want to rotate the automatically-generated x-axis labels of my plot in order to prevent the labels from overlapping:
I have been advised that matplotlib.pyplot.setp is worth a look, but I don't know how to use it in conjunction with labels that are generated automatically.
How can I rotate these labels?
x = [element[0] for element in eventDuplicates]
y = [element[1] for element in eventDuplicates]
figure = matplotlib.pyplot.figure()
figure.suptitle("event duplicates", fontsize = 20)
matplotlib.pyplot.scatter(x, y, s = 1, alpha = 1)
axes = matplotlib.pyplot.gca()
axes.yaxis.set_major_formatter(FormatStrFormatter("%.0f"))
axes.xaxis.set_major_formatter(FormatStrFormatter("%.0f"))
axes.set_xlim(left = 0)
#axes.set_ylim(bottom = 0)
#matplotlib.pyplot.setp(rotation = 90) # <--- insert magic here
matplotlib.pyplot.xlabel("run numbers")
matplotlib.pyplot.ylabel("event numbers")
matplotlib.pyplot.savefig("diagnostic_event_duplicates_scatter.png")
Something like this?
import numpy as np
import matplotlib.pylab as pl
import matplotlib as mpl
mpl.rcParams['axes.formatter.useoffset'] = False
x = np.arange(10000000, 10000010, 1)
y = np.cos(x)
pl.figure()
pl.subplot(121)
pl.plot(x,y)
pl.subplot(122)
pl.plot(x,y)
locs, labels = pl.xticks()
pl.setp(labels, rotation=90)

Categories

Resources