1

I am trying to plot a five colum dat file into two subplots using matplotlib. First colum from the dat file will be same for both the subplots. I could read the dat file in matplotlib but it is plotting only first three colums only (only one plot).

My file is sigma.dat with below entries

   0.013610  0.719520E-01  0.774371E-01  0.126304E-02  0.133856E-02
   0.040820  0.218942E+00  0.235756E+00  0.384315E-02  0.407507E-02
   0.068030  0.370247E+00  0.398893E+00  0.649864E-02  0.689443E-02
   0.095240  0.526034E+00  0.567041E+00  0.923211E-02  0.979962E-02
   0.122450  0.686473E+00  0.740396E+00  0.120463E-01  0.127937E-01
   0.149660  0.851747E+00  0.919171E+00  0.149441E-01  0.158801E-01
   0.176870  0.102205E+01  0.110358E+01  0.179285E-01  0.190620E-01
   0.204090  0.119764E+01  0.129394E+01  0.210038E-01  0.223444E-01
   0.231300  0.137860E+01  0.149035E+01  0.241710E-01  0.257286E-01
   0.258510  0.156522E+01  0.169312E+01  0.274349E-01  0.292199E-01
   0.285720  0.175773E+01  0.190255E+01  0.307990E-01  0.328224E-01
   0.312930  0.195639E+01  0.211891E+01  0.342672E-01  0.365405E-01
   0.340140  0.216143E+01  0.234251E+01  0.378436E-01  0.403789E-01
   0.367350  0.237315E+01  0.257367E+01  0.415324E-01  0.443426E-01
   0.394570  0.259192E+01  0.281281E+01  0.453396E-01  0.484383E-01
   0.421780  0.281787E+01  0.306012E+01  0.492672E-01  0.526684E-01

I tried to plot it with a small script but I am getting only single plot.

import numpy as np
import matplotlib.pyplot as pl
with open("sigma.dat", "r") as f:
    x = []
    y1 = []
    y2 = []
    for line in f:
        if not line.strip() or line.startswith('@') or line.startswith('#'):
            continue
        row = line.split()
        x.append(float(row[0]))
        y1.append(float(row[1]))
        y2.append(float(row[2]))

    pl.plot(x, y1, x, y2)
    pl.savefig("sigma.p`enter code here`ng", dpi=300)

I want to know how to plot this five colum dat file into two subplots, like clm:0:1:2; and clm:0:3:4. I expect the output image file should be having two subplots (2 1) with a space between both of them in one and no space between two subplots in another image.

3
  • 2
    PLease note that the common import abbreviation for matplotlib.pyplot is plt. Commented Sep 9, 2019 at 12:39
  • Would you consider using pandas for this? If you don't mind the overhead, it will make the code to read your file trivial. Commented Sep 9, 2019 at 13:03
  • Thanks dear Dan for your kind response. I am following the answer from SpghttCd in pondas. have a look at the conversation. Commented Sep 10, 2019 at 19:06

1 Answer 1

1

In matplotlib subplots() is the first address for generating multiple plots into one figure.
(See link for description and examples.)

So you could do

fig, axs = pl.subplots(2)
axs[0].plot(x, y1)
axs[1].plot(x, y2)

instead of your plot command above.


However, please note that while reading a file like this is possible and correct, there are several tools which help you here so you do not have to program this very common task manually again and again.

The most important tools are imo numpy and pandas, perhaps you heard already about them and like to try yourself.

With numpy you could do

import numpy as np
import matplotlib.pyplot as plt

data = np.genfromtxt("sigma.dat")

fig, axs = plt.subplots(2)
for i, ax in enumerate(axs):
    ax.plot(data[:, 0], data[:, i+1])

With pandas you could do

import pandas as pd

df = pd.read_csv("sigma.dat", delim_whitespace=True, index_col=0)
df.plot(subplots=True)

Short Explanation:

With numpy, you import an additional library along with matplotlib, which helps you not only with reading data from files, but which is in fact the basic needed library to do scientific math and calculations in python.

pandas on the other hand can replace matplotlib and/or numpy, as it is built on top of both. It is a complete data analysis tool with a wide range of functions included for a variaty of standard approaches in this topic.


Edit:

After reading your next question, I think I understand a little more of your task, so this is an approach in Python to create four subplots with no space in between:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('sigma.dat', delim_whitespace=True, index_col=0, header=None)

fig, axs = plt.subplots(2, 2, sharex=True, sharey='row', gridspec_kw={'hspace': 0, 'wspace': 0})

axs[0, 0].plot(df[df.columns[:2]])
axs[0, 1].plot(df[df.columns[:2]]*1.2)
axs[1, 0].plot(df[df.columns[2:]])
axs[1, 1].plot(df[df.columns[2:]]*.75)

enter image description here


EDIT2:

Further attempt to copy this handmade original

import matplotlib as mpl
mpl.rcParams['font.family'] = 'Times New Roman'

fig, axs = plt.subplots(2, 2, sharex=True, gridspec_kw={'hspace': 0, 'wspace': 0})

axs[0, 0].plot(df[df.columns[:2]])
axs[0, 1].plot(df[df.columns[:2]]*1.2)
axs[1, 0].plot(df[df.columns[2:]])
axs[1, 1].plot(df[df.columns[2:]]*.75)
for i in range(2):
    axs[i, 1].spines['left'].set_position(('axes', 1))
    axs[i, 1].yaxis.set_ticks_position('right')
    axs[i, 1].yaxis.set_label_position('right')

axs[0, 0].set_ylabel('A11')
axs[0, 1].set_ylabel('A12')
axs[1, 0].set_ylabel('A21')
axs[1, 1].set_ylabel('A22')

for ax, lbl in zip(axs.flatten(), list('abcd')):
    ax.text(.05, .9, f'({lbl})', transform=ax.transAxes)
axs[1, 0].set_xlabel('X-12-Scale', x=1)

enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

Dear SpghttCd, your code" import numpy as np import matplotlib.pyplot as plt data = np.genfromtxt("sigma.dat") fig, axs = plt.subplots(2) for i, ax in enumerate(axs): ax.plot(data[:, 0], data[:, i+1])" worked for me but not as per what I am looking for. I want to plot the column 0,1, 2 in one subplot while colum 0,4,5 in other subplot. with axis lables, title at center top and center bottom and figure numbers like (a), (b).
Sorry - I read as stated above your next question, but didn't see your comment - only on mobile the last hours... However, perhaps the new pandas code eirks for you too, it includes plotting of the first 2 columns in s different axis than the last 2. But of course I can check sth similar for the numpy based script.
Yes, this pondas is working now for me. Could you please modify it so that I can get the plot as asked by me i.sstatic.net/SAjW7.jpg . If possible please take care of tick fonts and tick labels as asked in the above link. It would be a great help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.