Code Monkey home page Code Monkey logo

ternary_diagram's Introduction

Ternary Diagram

python_badge license_badge PyPI version Downloads

Test on each version Code style: black conda_badge arch_badge

This package makes it easier for you to draw beautiful ternary diagram without pymatgen.

Meaningly, only need numpy and matplotlib.

What you will be able to do with this package

  • Create beautiful contour maps easily
  • Creating a scatter plot
  • Draw tie lines
  • Automatically format chemical composition using subscripts
  • Most of the matplotlib options are available

/example/contour/example_contour.png

How to install

PyPI

pip install ternary-diagram

PyPI project is here.

Anaconda

conda install -c conda-forge ternary-diagram

Anaconda (conda-forge) package site is here.

Usage

See Examples and the documentation.

Examples

An easy example is here.

import matplotlib.pyplot as plt
from ternary_diagram import TernaryDiagram

# You can set `ax` to select which axes to draw. If not, the current axes will be used.
td = TernaryDiagram(["Li2O", "La2O3", "TiO2"])

# scatter
td.scatter(vector=[[1, 1, 1], [1, 2, 3]], z=[0, 1])
# You can set some options in `plt.scatter` like `marker`, `c` etc.
td.scatter(vector=[[2, 1, 3], [3, 2, 1]], marker="s", c="#022c5e", s=30)

# line plot
# You can set some options in `plt.plot` like `lw`, `c`, and so on.
td.plot([[1, 1, 1], [1, 2, 3]], color="black")

# save figure
td.fig.savefig("figure.png", dpi=144)

/example/example_on_readme/figure.png

It can be written like this.

# The background color is sometimes transparent in jupyter notebooks, so set facecolor 'white'.
fig, ax = plt.subplots(facecolor="w")

# You can set `ax` to select which axes to draw. If not, the current axes will be used.
td = TernaryDiagram(["Li2O", "La2O3", "TiO2"], ax=ax)

# scatter
td.scatter(vector=[[1, 1, 1], [1, 2, 3]], z=[0, 1])
# You can set some options in `plt.scatter` like `marker`, `c` etc.
td.scatter(vector=[[2, 1, 3], [3, 2, 1]], marker="s", c="#022c5e", s=30)

# line plot
# You can set some options in `plt.plot` like `lw`, `c`, and so on.
td.plot([[1, 1, 1], [1, 2, 3]], color="black")

# save figure
fig.savefig("figure.png", dpi=144)

It means that you can draw multiple figures in one figure object.

See also the example folder.

Histories

v3.1.0

  • Delete .utils._BasePlotter.get_x_y (we should access directly).
  • Resolve #10 (Create fill argument in TernaryDiagram.contour).
  • Resolve #11 (Create auto_latex_notation argument in TernaryDiagram).
  • Update documentation.
  • Update docstrings and typings.

LICENSE

See LICENSE.

MIT Licence

Copyright (c) 2021 yu9824

ternary_diagram's People

Contributors

yu9824 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Forkers

francescapelusi

ternary_diagram's Issues

The error occurs when there is only one uniform value.

I believe that this problem stems from the fact, the upper and lower limits are the same value rather than the homogeneousness of data.

import numpy as np
from ternary_diagram import TernaryDiagram

td = TernaryDiagram(['Li2O', 'TiO2', 'La2O3'])

np.random.seed(334)
n_samples = 100
ratio = np.random.rand(n_samples, 3)
z = np.ones(n_samples)

td.contour(ratio, z=z)

Error message is here.

ValueError: Contour levels must be increasing
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-7-1baff06f772a> in <module>
     13     )
     14 
---> 15     module.predict(
     16         materials=['Li2O', 'SiO2', 'MoO3'],
     17         compositions=[],

/conductivity_prediction/main.py in predict(self, materials, compositions, path_dir)
    584 
    585             td = TernaryDiagram(materials = df_ratio.columns)
--> 586             td.contour(vector = df_ratio, z = y_pred)
    587             td.fig.savefig(os.path.join(path_output_img, '{0}.{1}'.format('-'.join(materials), 'png')), dpi = 300, transparent = False)
    588             plt.close()

/opt/conda/lib/python3.8/site-packages/ternary_diagram/ternary_diagram.py in contour(self, vector, **options)
    285             percentage of each compound mixed in 2D list / pandas.DataFrame / numpy.ndarray, where shape = [n, 3] (n is the number of samples to be plotted as integer)
    286         '''
--> 287         self._contour_(self, vector, **options) # selfオブジェクトを渡してる.
    288 
    289     def plot(self, r1, r2, **options):   # 連結線を引く (scatterオブジェクトの使用が必須な状況)

/opt/conda/lib/python3.8/site-packages/ternary_diagram/ternary_diagram.py in __init__(self, outer, vector, **options)
    238 
    239             T = tri.Triangulation(self.x, self.y)
--> 240             self.triplot = outer.ax.tricontourf(self.x, self.y, T.triangles, self.z, np.linspace(self.minimum if self.minimum is not None else np.min(self.z), self.maximum if self.maximum is not None else np.max(self.z), 101), **self.options)
    241             self.colorbar()
    242             self.tight_layout()

/opt/conda/lib/python3.8/site-packages/matplotlib/tri/tricontour.py in tricontourf(ax, *args, **kwargs)
    319     """
    320     kwargs['filled'] = True
--> 321     return TriContourSet(ax, *args, **kwargs)

/opt/conda/lib/python3.8/site-packages/matplotlib/tri/tricontour.py in __init__(self, ax, *args, **kwargs)
     38         are described in the docstring of `~.Axes.tricontour`.
     39         """
---> 40         ContourSet.__init__(self, ax, *args, **kwargs)
     41 
     42     def _process_args(self, *args, **kwargs):

/opt/conda/lib/python3.8/site-packages/matplotlib/contour.py in __init__(self, ax, levels, filled, linewidths, linestyles, hatches, alpha, origin, extent, cmap, colors, norm, vmin, vmax, extend, antialiased, nchunk, locator, transform, *args, **kwargs)
    814         self._transform = transform
    815 
--> 816         kwargs = self._process_args(*args, **kwargs)
    817         self._process_levels()
    818 

/opt/conda/lib/python3.8/site-packages/matplotlib/tri/tricontour.py in _process_args(self, *args, **kwargs)
     50         else:
     51             from matplotlib import _tri
---> 52             tri, z = self._contour_args(args, kwargs)
     53             C = _tri.TriContourGenerator(tri.get_cpp_triangulation(), z)
     54             self._mins = [tri.x.min(), tri.y.min()]

/opt/conda/lib/python3.8/site-packages/matplotlib/tri/tricontour.py in _contour_args(self, args, kwargs)
    105         if self.logscale and self.zmin <= 0:
    106             raise ValueError('Cannot %s log of negative values.' % fn)
--> 107         self._process_contour_level_args(args[1:])
    108         return (tri, z)
    109 

/opt/conda/lib/python3.8/site-packages/matplotlib/contour.py in _process_contour_level_args(self, args)
   1170 
   1171         if len(self.levels) > 1 and np.min(np.diff(self.levels)) <= 0.0:
-> 1172             raise ValueError("Contour levels must be increasing")
   1173 
   1174     def _process_levels(self):

ValueError: Contour levels must be increasing

Add options related to composition or not?

At present, the program automatically adds subscripts to the text entered as materials and various other text.

However, for extensibility, we think it should be possible to select the subscript by using flag.

For example,

td = TernaryDiagram(materials=['Li2O', 'La2O3', 'TiO2'], flag_composition = False)

etc.

For td.annotate in particular, we think it should be recognized as normal text by default. In particular, for td.annotate, we think it should be recognized as normal text by default, because it is easy to create subscripts using ternary_diagram.utils.get_label function.

Modify error about contour function.

from ternary_diagram import TernaryDiagram
import numpy as np

ratio = np.random.rand(100, 3)

td = TernaryDiagram(materials = ['Li2O', 'TiO2', 'La2O3'])
td.contour(ratio)

Error statement here.

AttributeError: '_contour_' object has no attribute 'minimum'
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-3-a6f20240bea1> in <module>
      1 td = TernaryDiagram(materials = ['Li2O', 'TiO2', 'La2O3'])
----> 2 td.contour(ratio)

~/ternary_diagram/ternary_diagram/ternary_diagram.py in contour(self, vector, **options)
    285             percentage of each compound mixed in 2D list / pandas.DataFrame / numpy.ndarray, where shape = [n, 3] (n is the number of samples to be plotted as integer)
    286         '''
--> 287         self._contour_(self, vector, **options) # selfオブジェクトを渡してる.
    288 
    289     def plot(self, r1, r2, **options):   # 連結線を引く (scatterオブジェクトの使用が必須な状況)

~/ternary_diagram/ternary_diagram/ternary_diagram.py in __init__(self, outer, vector, **options)
    238 
    239             T = tri.Triangulation(self.x, self.y)
--> 240             self.triplot = outer.ax.tricontourf(self.x, self.y, T.triangles, self.z, np.linspace(self.minimum if self.minimum is not None else np.min(self.z), self.maximum if self.maximum is not None else np.max(self.z), 101), **self.options)
    241             self.colorbar()
    242             self.tight_layout()

AttributeError: '_contour_' object has no attribute 'minimum'

You should encourage the programmer to improve by issuing an error message "You must enter 'z'." if he does not enter 'z' when the contour function is called.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.