File: plot.py

package info (click to toggle)
python-ase 3.12.0-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 14,192 kB
  • ctags: 8,112
  • sloc: python: 93,375; sh: 99; makefile: 94
file content (72 lines) | stat: -rw-r--r-- 1,967 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
from ase.io.png import write_png
from ase.utils import basestring


def atoms2png(atoms, filename):
    if atoms:
        size = atoms.positions.ptp(0)
        i = size.argmin()
        rotation = ['-90y', '90x', ''][i]
        size[i] = 0.0
        scale = min(20, 20 / size.max() * 10.0)
    else:
        scale = 20
        rotation = ''
    write_png(filename, atoms, show_unit_cell=1,
              rotation=rotation, scale=scale)

    
def dct2plot(dct, name, filename=None, show=True):
    """Create a plot from a dict.
    
    Example::
        
        d = {'a': [0, 1, 2],
             'b': [1.2, 1.1, 1.0],
             'abplot': {'title': 'Example',
                        'data': [{'x': 'a',
                                  'y': 'b',
                                  'label': 'label1',
                                  'style': 'o-g'}],
                        'xlabel': 'blah-blah [eV]'}}
        dct2plot(d, 'plot')
        
    """
    import matplotlib.pyplot as plt
    fig = plt.figure()
    styles = ['k-', 'r-', 'g-', 'b-']
    plot = dct[name]
    lines = []
    labels = []
    for d in plot['data']:
        x = d['x']
        if isinstance(x, basestring):
            x = dct[x]
        y = d['y']
        if isinstance(y, basestring):
            y = dct[y]
        style = d.get('style')
        if not style:
            style = styles.pop()
        lines.append(plt.plot(x, y, style)[0])
        labels.append(d['label'])
    plt.legend(lines, labels)
    if isinstance(plot['xlabel'], basestring):
        plt.xlabel(plot['xlabel'])
    else:
        x, labels = plot['xlabel']
        plt.xticks(x, labels)
        plt.xlim(x[0], x[-1])
    plt.ylabel(plot['ylabel'])
    if 'ylim' in plot:
        plt.ylim(*plot['ylim'])
    plt.title(plot['title'])
    try:
        plt.tight_layout()
    except AttributeError:
        pass
    if show:
        plt.show()
    if filename:
        plt.savefig(filename)
        plt.close(fig)