How to save plt image to local in python - python

I'm trying to save my plotted image to local, I've tried to follow some tutorials from the internet, but still can't, can anyone help me?
import pandas as pd
import matplotlib.pyplot as plt
joined_data = pd.read_csv('/content/drive/MyDrive/Kurs/clean_data/forecast.csv')
# First plot
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(20,8))
ax1.plot(joined_data["kurs_jual"])
ax1.set_xlabel("Tanggal", fontsize=12)
ax1.set_ylabel("Kurs Jual")
ax1.set_title("Kurs Jual VND")
# second plot
ax2.plot(joined_data["kurs_beli"], color="orange")
ax2.set_xlabel("Tanggal", fontsize=12)
ax2.set_ylabel("Kurs Beli")
ax2.set_title("Kurs Beli VND")
plt.show()
plt.savefig('/content/drive/MyDrive/Kurs/clean_data/forecast_vnd.png')

Use plt.savefig('/content/drive/MyDrive/Kurs/clean_data/forecast_vnd.png') before plt.show() else the saved picture would be blank.

Related

Plotting Errorbars from different DataFrame into SubPlots with matplotlib

i just stumpled upon a problem I simply cannot solve. I have a dataset with raw data which I will upload here: https://file.io/oJqkZjAGyqV1
Its an excel file with the data inside.
I then created some code to open it, read it, generate a mean and sem of my data as below.
# Import required packages
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from pylab import cm
df = pd.read_excel("Chlorophyll_data_mod.xlsx")
#----Calculation of meanvalues and sem from raw_data---------
meandf2 = df.set_index(["Group"])
sets = []
for x in ["A","B","AB","xc"]:
meandf3 = meandf2.filter(like=f"Chl_{x}_").reset_index()
sets.append(meandf3)
#---------Grouping DataFrame----------#
means = []
ster = []
for x in range(len(sets)):
meandf = sets[x].groupby(["Group"]).mean()
meandf = meandf.reset_index()
means.append(meandf)
sems = sets[x].groupby("Group").sem()
sems = sems.reset_index()
ster.append(sems)
#----Selecting Dataframe from List-----#
plotdf = means[0]
ploter = ster[0]
plotgroup = plotdf.iloc[:,[0,]]
plotdata = plotdf.iloc[:,[1,]]
grouparray = plotgroup.to_numpy()
dataarray = plotdata.to_numpy()
#-----CreatePlot------#
fig, ax = plt.subplots(nrows=3, ncols=1, sharex="all", figsize=(10,8))
plotdf.plot(ax=ax[0,],x="Group",y="Chl_A_0D", kind="bar", legend=False, color="black")
plt.errorbar(x=plotdf["Group"], y=plotdf["Chl_A_0D"],yerr=ploter["Chl_A_0D"])
plotdf.plot(ax=ax[1,],x="Group",y="Chl_A_10DaT", kind="bar", legend=False, color="blue")
plt.errorbar(x=plotdf["Group"], y=plotdf["Chl_A_10DaT"],yerr=ploter["Chl_A_10DaT"])
plotdf.plot(ax=ax[2,],x="Group",y="Chl_A_7DaR", kind="bar", legend=False, color="magenta")
plt.errorbar(x=plotdf["Group"], y=plotdf["Chl_A_7DaR"],yerr=ploter["Chl_A_7DaR"])
#----Legend of the Plot-----#
fig.legend(loc="lower center", bbox_to_anchor=(0.5,0), fancybox=True, ncol=6)
#----Layout------#
plt.tight_layout(rect=[0, 0.02, 1,1])
plt.show()
And I manage to create a subplot, which shows 3 of my interested data points. However, I struggle with the error bars.
My approach was to calculate the sem and store it into a new dataframe. And then just read it from there for the yerr. However, this doesn't work.
plotdf.plot(ax=ax[2,],x="Group",y="Chl_A_7DaR", kind="bar", legend=False, color="magenta", yerr=ploter["Chl_A_7DaR"])
Results in an array error because of the structure.
And my current approach, as in the main code above only draws the error bars in the last subplot, but not in each individual plot.
Maybe here is someone who could help me understanding this function?
Best regards

I want to make interpolated heatmap with data from excel

I want to create a heat map similar to the picture below using data from an excel sheet.
enter image description here
I tried to use this code below but swap the np.random.seed for data from the excel but it doesnt work. The excel consists of 2 columns and 4 rows of data.
someone please help. Im new to coding and this is super frustrating.
import matplotlib.pyplot as plt
import numpy as np
methods = [None, 'none', 'sinc']
# Fixing random state for reproducibility
np.random.seed(19680801)
grid = np.random.rand(4, 4)
fig, axs = plt.subplots(nrows=3, ncols=6, figsize=(9, 6),
subplot_kw={'xticks': [], 'yticks': []})
for ax, interp_method in zip(axs.flat, methods):
ax.imshow(grid, interpolation=interp_method, cmap='viridis')
ax.set_title(str(interp_method))
plt.tight_layout()
plt.show()

sns matplotlib output slicing the saved image [duplicate]

This question already has answers here:
Plt.show shows full graph but savefig is cropping the image
(3 answers)
Closed 1 year ago.
I am trying to save sns matplotlib output as jpg file and reopen it with cv2.
but i am facing distinct data loss, would someone help me to resolve, i tried in several savefig options and documentations.
sample code
import pandas as pd
import numpy as np
import cv2
import seaborn as sns
import matplotlib.pyplot as plt
by_c = None
fig = plt.Figure(figsize=(5, 4), dpi=100)
g = sns.FacetGrid(pd.DataFrame(np.random.random(10)*150, columns=['col']), col=None, row=None, height=3.5, aspect=1)
g.map_dataframe(sns.histplot, x='col')
plt.title('col'+' - '+str(by_c)+'-', fontsize=12)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.savefig('temp.png')
plt.show()
Out:
Saved picture example of 'temp.png'
out:
reopening image
im = cv2.imread('temp.png')
plt.imshow(im)
Out1:
Image title and lables sliced bit, i am not sure how else i can save it. Would someone please help to resolve it
To set the quality of the image use the dpi, and also specify the bbox_inches for a full layout. If not, it will consider the nearest view of the image
import pandas as pd
import numpy as np
import cv2
import seaborn as sns
import matplotlib.pyplot as plt
by_c = None
fig = plt.Figure(figsize=(5, 4), dpi=100)
g = sns.FacetGrid(pd.DataFrame(np.random.random(10)*150, columns=['col']), col=None, row=None, height=3.5, aspect=1)
g.map_dataframe(sns.histplot, x='col')
plt.title('col'+' - '+str(by_c)+'-', fontsize=12)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.savefig('temp.png',dpi=300, bbox_inches = "tight")
#plt.savefig('temp.png')
plt.show()
im = cv2.imread('temp.png')
plt.imshow(im)
Resultant Image:

How to fix 'AttributeError: Unknown property figsize'?

I am trying to plot multiple graphs into 1 using a for loop and I encountered this problem. I tried it for the other loops and it works just fine but I don't know what happened with this one.
The files used are the exchange rates of EUR to USD for the past 2 years and I am trying to plot the date and the price on the graph. If I don't use figsize the graph is too small but it works.
import pandas as pd
import matplotlib.pyplot as plt
file = ['somefile.csv', 'otherfile.csv', 'anotherfile.csv']
for files in file:
files1 = pd.read_csv ('%s' %files)
files1.plot (kind='line', x='Date', y='Price', ax=ax, figsize=(15,10))
plt.legend()
plt.show()
One way around is using
plt.gcf().set_size_inches(15, 8)
So your code should be
import pandas as pd
import matplotlib.pyplot as plt
file = ['somefile.csv', 'otherfile.csv', 'anotherfile.csv']
for files in file:
files1 = pd.read_csv ('%s' %files)
files1.plot (kind='line', x='Date', y='Price', ax=ax)
plt.gcf().set_size_inches(15, 8))
plt.legend()
plt.show()
Use the following: Create first the axis object specifying the figure size and then use that object while plotting
fig, ax = plt.subplots(figsize=(15,10))
for files in file:
files1 = pd.read_csv ('%s' %files)
files1.plot (kind='line', x='Date', y='Price', ax=ax)
Since you want to specify axis as ax(ax=ax), best answer would be #Sheldore's. But there's actually an easier, also the most basic, way to this:
plt.figure(figsize=(15,10))
Put this before the for loop.

Need to save pandas correlation Highlighted table (cmap Matplotlib) as png image

Used this code to genrate corelation table:
df1.drop(['BC DataPlus', 'AC Glossary'], axis=1).corr(method='pearson').style.format("{:.2}").background_gradient(cmap=plt.get_cmap('coolwarm'), axis=1)
This is the table generated:
I cant find any way to save this table as image. Thank you.
The question you pose is difficult to answer if taken literally.
The difficulty stems from the fact that df.style.render() generates HTML which is then sent to a browser to be rendered as an image. The result may not be exactly the same across all browsers either.
Python is not directly involved in the generation of the image. So there is no
straight-forward Python-based solution.
Nevertheless, the issue of how to convert HTML to png
was raised on the pandas developers'
github page and the suggested
answer was to use phantomjs. Other ways (that I haven't tested) might be to use
webkit2png or
GrabzIt.
We could avoid much of this difficulty, however, if we loosen the interpretation of the question. Instead of trying to produce the exact image generated by df.style (for a particular browser),
we could generate a similar image very easily using seaborn:
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.random((6, 4)), columns=list('ABCD'))
fig, ax = plt.subplots()
sns.heatmap(df.corr(method='pearson'), annot=True, fmt='.4f',
cmap=plt.get_cmap('coolwarm'), cbar=False, ax=ax)
ax.set_yticklabels(ax.get_yticklabels(), rotation="horizontal")
plt.savefig('result.png', bbox_inches='tight', pad_inches=0.0)
If you don't want to add the seaborn dependency, you could use matplotlib directly though it takes a few more lines of code:
import colorsys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.random((6, 4)), columns=list('ABCD'))
corr = df.corr(method='pearson')
fig, ax = plt.subplots()
data = corr.values
heatmap = ax.pcolor(data, cmap=plt.get_cmap('coolwarm'),
vmin=np.nanmin(data), vmax=np.nanmax(data))
ax.set_xticks(np.arange(data.shape[1])+0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0])+0.5, minor=False)
ax.invert_yaxis()
row_labels = corr.index
column_labels = corr.columns
ax.set_xticklabels(row_labels, minor=False)
ax.set_yticklabels(column_labels, minor=False)
def _annotate_heatmap(ax, mesh):
"""
**Taken from seaborn/matrix.py**
Add textual labels with the value in each cell.
"""
mesh.update_scalarmappable()
xpos, ypos = np.meshgrid(ax.get_xticks(), ax.get_yticks())
for x, y, val, color in zip(xpos.flat, ypos.flat,
mesh.get_array(), mesh.get_facecolors()):
if val is not np.ma.masked:
_, l, _ = colorsys.rgb_to_hls(*color[:3])
text_color = ".15" if l > .5 else "w"
val = ("{:.3f}").format(val)
text_kwargs = dict(color=text_color, ha="center", va="center")
# text_kwargs.update(self.annot_kws)
ax.text(x, y, val, **text_kwargs)
_annotate_heatmap(ax, heatmap)
plt.savefig('result.png', bbox_inches='tight', pad_inches=0.0)

Categories

Resources