Home > Blockchain >  Saving histogram as jpg in Python
Saving histogram as jpg in Python

Time:10-01

I have an array r. I want to save the histogram as A.jpg but it is not saving anything. Instead, I am getting an error shown below.

import numpy as np
import pandas as pd

r=np.array([54.3817864 , 50.70031442, 53.63511598, 49.6935623 , 51.80017684,
       52.80854701, 50.18808714, 51.85747597, 47.94544424, 49.59728558,
       53.42810469, 54.3817864 ])

with open("A.jpg", 'w ') as f: 
    r=pd.Series(r)
    r.hist()
    print(r)

The error is

Sorry, Photos can't open this file because the format is currently unsupported, or the file is corrupted.

CodePudding user response:

Use matplotlib library to save plot as a jpg/png.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

r=np.array([54.3817864 , 50.70031442, 53.63511598, 49.6935623 , 51.80017684,
   52.80854701, 50.18808714, 51.85747597, 47.94544424, 49.59728558,
   53.42810469, 54.3817864 ])

plt.hist(r)
plt.savefig("r.jpg")

CodePudding user response:

you can try this:

import matplotlib.pyplot as plt
import Image
import numpy as np
import pandas as pd

r=np.array([54.3817864 , 50.70031442, 53.63511598, 49.6935623 , 51.80017684,
       52.80854701, 50.18808714, 51.85747597, 47.94544424, 49.59728558,
       53.42810469, 54.3817864 ])

plt.hist(r)
plt.savefig('A.png')
Image.open('A.png').save('A.jpg','JPEG')

CodePudding user response:

If I understand correctly, you want to save your picture A.jpgm but you're getting the error Sorry, Photos can't open this file because the format is currently unsupported, or the file is corrupted. (which I have verified, with your suggested code, you get that error indeed).

If so, try the following code:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

r=np.array([54.3817864 , 50.70031442, 53.63511598, 49.6935623 , 51.80017684,
       52.80854701, 50.18808714, 51.85747597, 47.94544424, 49.59728558,
       53.42810469, 54.3817864 ])

r=pd.Series(r)
r.hist()
plt.savefig('A.jpg')  # Or use your own path

It should open now. Hope it helps.

CodePudding user response:

I think using "savefig" will fix this problem:

   import numpy as np
   import pandas as pd

   r=np.array([54.3817864 , 50.70031442, 53.63511598, 49.6935623 , 51.80017684,
   52.80854701, 50.18808714, 51.85747597, 47.94544424, 49.59728558,
   53.42810469, 54.3817864 ])

   r=pd.Series(r)
   ax=r.plot.hist()
   print(r)
   ax.figure.savefig("A.png")

I don't think you can save it in jpg format through this but you can use "Image" library to convert png to jpg

  • Related