0

This code will create a 3d scatter plot using matplotlib and I am trying to figure out how to save a PNG with the same name as the CSV file I am using to create the pandas dataframe.

I can save the PNG same name as the .py file with this:

output_filename = os.path.splitext(__file__)[0] + '.png'

But how do I modify the code to save the PNG same name as the CSV file?

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import pandas as pd
import os


output_filename = os.path.splitext(__file__)[0] + '.png'


df = pd.read_csv('RTU_101A_Month2dataCSV.csv',index_col='Date', parse_dates=True)

OAT = pd.Series(df['OAT'])
RAT = pd.Series(df['RAT'])
MAT = pd.Series(df['MAT'])
df['hour'] = df.index.hour

df_OATrat = (OAT - RAT)
df_MATrat = (MAT - RAT)
df_Hour = df['hour']

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x = df_MATrat
y = df_Hour
z = df_OATrat

ax.scatter(x, y, z, c='g', marker='x')

ax.set_xlabel('MAT-RAT')
ax.set_ylabel('Hours in Day')
ax.set_zlabel('OAT-RAT')

plt.show()
plt.savefig(output_filename)
bbartling
  • 3,288
  • 9
  • 43
  • 88

1 Answers1

0

Since you are explicitly specifying the name of the csv file while reading it, why can't you simply do the following. Remember, comment out the plt.show() before saving the figure. Read here more on why plt.savefig() saves a blank figure if used after plt.show()

csv_file = 'RTU_101A_Month2dataCSV.csv'

df = pd.read_csv(csv_file, index_col='Date', parse_dates=True)

# Your code
# plt.show() # <--- Comment this out when saving
plt.savefig(csv_file.split('.csv')[0] + '.png')

# plt.savefig(csv_file.split('.csv')[0], format='png')

Assuming you have only one csv file in the current directory, you can also do the following as shown here to get the csv file name

import glob, os
os.chdir(".")
for file in glob.glob("*.csv"):
    csv_file = file.split('.csv')[0]

# Your code

# plt.show() # <--- Comment this out when saving
plt.savefig(csv_file + '.png')
Sheldore
  • 37,862
  • 7
  • 57
  • 71
  • Thanks for the tips, the code definitely saves a PNG the same name as the CSV file but they are blank when opened. Is that matplotlib thing? On your first answer post where another save option is commented out, when I try both options they do the same thing. Saves a blank PNG file.. No errors lilke the script executes just fine – bbartling Jun 14 '19 at 17:16
  • @HenryHub : Comment out the `plt.show()` and try again – Sheldore Jun 14 '19 at 17:17