Example #1
0
def simple_violin():
    df = load_dataset("elastic_tensor_2015")
    pf = PlotlyFig(df,
                   title="Distribution of Elastic Constant Averages",
                   colorscale='Reds')
    pf.violin(cols=['K_Reuss', 'K_Voigt', 'G_Reuss', 'G_Voigt'],
              use_colorscale=True)
Example #2
0
def advanced_bar():
    """
    Compare the number of sites in the unit cell and eij_max of the first 5
    samples from the piezoelectric_tensor dataset.
    """
    # Format the general layout of our figure with 5 samples
    pf = PlotlyFig(df=load_dielectric_constant().iloc[:5],
                   title='Comparison of 5 materials band gaps and n')
    # Plot!
    colors = ['red', 'orange', 'yellow', 'blue', 'green']
    pf.bar(cols=['n', 'band_gap'], labels='formula', colors=colors)
Example #3
0
def plot_basic_heatmap():
    """
    Very basic heatmap plot when the data is already in the right format.
    Duplicate example; see https://plot.ly/python/heatmaps/ for more info

    Returns:
        plotly plot in "offline" mode poped in the default browser.
    """
    pf = PlotlyFig(filename='heatmap_basic')
    z=[[1, 20, 30, 50, 1], [20, 1, 60, 80, 30], [30, 60, 1, -10, 20]]
    x=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
    y=['Morning', 'Afternoon', 'Evening']
    pf.heatmap_basic(z, x_labels=x, y_labels=y)
Example #4
0
def plot_basic_heatmap():
    """
    Very basic heatmap plot when the data is already in the right format.
    Duplicate example; see https://plot.ly/python/heatmaps/ for more info

    Returns:
        plotly plot in "offline" mode poped in the default browser.
    """
    pf = PlotlyFig(filename='heatmap_basic')
    z = [[1, 20, 30, 50, 1], [20, 1, 60, 80, 30], [30, 60, 1, -10, 20]]
    x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
    y = ['Morning', 'Afternoon', 'Evening']
    pf.heatmap_basic(z, x_labels=x, y_labels=y)
Example #5
0
def plot_simple_heatmap_df():
    """
    Very basic example shows how heatmap_df takes a dataframe and returns
    an overview heatmap of the data with the help of pandas.qcut

    Returns:
        plotly plot in "offline" mode poped in the default browser.
    """
    a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    b = [2, 4, 6, 8, 10, 2, 4, 6, 8, 10]
    c = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
    df = pd.DataFrame(data=np.asarray([a, b, c]).T,
                      columns=['var a', 'var b', 'var c'])
    pf = PlotlyFig(colorscale='Oregon')
    pf.heatmap_df(df, x_labels=['low','high'], y_labels=['q1','q2','q3','q4'])
Example #6
0
def plot_simple_heatmap_df():
    """
    Very basic example shows how heatmap_df takes a dataframe and returns
    an overview heatmap of the data with the help of pandas.qcut

    Returns:
        plotly plot in "offline" mode poped in the default browser.
    """
    a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    b = [2, 4, 6, 8, 10, 2, 4, 6, 8, 10]
    c = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
    df = pd.DataFrame(data=np.asarray([a, b, c]).T,
                      columns=['var a', 'var b', 'var c'])
    pf = PlotlyFig(colorscale='Oregon')
    pf.heatmap_df(df,
                  x_labels=['low', 'high'],
                  y_labels=['q1', 'q2', 'q3', 'q4'])
Example #7
0
def plot_boston_dataset_heatmap_df():
    """
    This example uses sklearn boston dataset to plot a heatmap based on the
    binned data to see if there is a relationship between the Median house
    value w/ air NOX concentration and CHAS (Charles River dummy variable)

    Returns:
        plotly plot in "offline" mode poped in the default browser.
    """
    boston = datasets.load_boston()
    df_boston = pd.DataFrame(boston['data'], columns=boston['feature_names'])
    df_boston['Median value'] = boston.target

    pf = PlotlyFig(fontscale=0.8, filename='boston', colorscale='RdBu')
    pf.heatmap_df(df_boston[['NOX', 'CHAS', 'Median value']],
                  x_nqs=4,
                  y_labels=['otherwise', 'tract bounds river'])
Example #8
0
def plot_mean_elastic_tensors():
    """
    An example of heatmap_df where the input data is real and in dataframe
    format. We want to look at how average of the elastic constant tensor
    changes with the density and crystal system. Note that density is not
    a categorical variable in the final dataframe.

    Returns:
        plotly plot in "offline" mode poped in the default browser.
    """
    df = load_elastic_tensor()
    # data preparation:
    df['Mean Elastic Constant'] = df['elastic_tensor'].apply(lambda x: np.mean(x))
    gs = GlobalSymmetryFeatures(desired_features=['crystal_system'])
    df = gs.featurize_dataframe(df, col_id='structure')
    dsf = DensityFeatures(desired_features=['density'])
    df = dsf.featurize_dataframe(df, col_id='structure')
    # actual plotting
    pf = PlotlyFig(fontscale=0.75, filename='static_elastic_constants', colorscale='RdBu')
    pf.heatmap_df(df[['crystal_system', 'density', 'Mean Elastic Constant']])
Example #9
0
def plot_scatter_matrix():
    """
    A few different scatter matrix plots using elastic dataset in matminer.
    Returns:
        plotly plot in "offline" mode opened in the default browser.
    """
    df = load_elastic_tensor()
    pf = PlotlyFig(df)

    # basic matrix:
    pf.scatter_matrix(cols=['K_VRH', 'G_VRH', 'nsites', 'volume'])

    # with colorscale and labels:
    pf.scatter_matrix(cols=['K_VRH', 'G_VRH', 'nsites', 'volume'],
                      colors='nsites',
                      labels='material_id',
                      colorscale='Picnic')

    # with all the numerical columns included (note the change in sizes):
    pf = PlotlyFig(filename='scatter_matrix_elastic', fontscale=0.6)
    pf.scatter_matrix(df, marker_scale=0.6)
Example #10
0
def plot_mean_elastic_tensors():
    """
    An example of heatmap_df where the input data is real and in dataframe
    format. We want to look at how average of the elastic constant tensor
    changes with the density and crystal system. Note that density is not
    a categorical variable in the final dataframe.

    Returns:
        plotly plot in "offline" mode poped in the default browser.
    """
    df = load_dataset("elastic_tensor_2015")
    # data preparation:
    df['Mean Elastic Constant'] = df['elastic_tensor'].apply(
        lambda x: np.mean(x))
    gs = GlobalSymmetryFeatures(desired_features=['crystal_system'])
    df = gs.featurize_dataframe(df, col_id='structure')
    dsf = DensityFeatures(desired_features=['density'])
    df = dsf.featurize_dataframe(df, col_id='structure')
    # actual plotting
    pf = PlotlyFig(fontscale=0.75,
                   filename='static_elastic_constants',
                   colorscale='RdBu')
    pf.heatmap_df(df[['crystal_system', 'density', 'Mean Elastic Constant']])
Example #11
0
def formatting_example(api_key, username):
    """
    Demonstrate common and advanced formatting features of PlotlyFig.

    PlotlyFig provides a set of arguments which make setting up good
    looking Plotly templates quick(er) and easy(er).

    Most formatting options can be set through the initializer of PlotlyFig.
    These options will remain the same for all figures producted, but you can
    change some common formatting options after instantitating a PlotlyFig
    object using set_arguments.

    Chart-specific formatting options can be passed to plotting methods.
    """

    if not api_key or not username:
        raise ValueError("Specify your Plotly api_key and username!")

    df = load_elastic_tensor()

    pf = PlotlyFig(df=df,
                   api_key=api_key,
                   username=username,
                   mode='online',
                   title='Comparison of Bulk Modulus and Shear Modulus',
                   x_title='Shear modulus (GPa)',
                   y_title='Bulk modulus (GPa)',
                   colorbar_title='Poisson Ratio',
                   fontfamily='Raleway',
                   fontscale=0.75,
                   fontcolor='#283747',
                   ticksize=30,
                   colorscale="Reds",
                   hovercolor='white',
                   hoverinfo='text',
                   bgcolor='#F4F6F6',
                   margins=110,
                   pad=10)

    pf.xy(('G_VRH', 'K_VRH'), labels='material_id', colors='poisson_ratio')

    # We can also use LaTeX if we use Plotly online/static
    pf.set_arguments(title="$\\text{Origin of Poisson Ratio } \\nu $",
                     y_title='$K_{VRH} \\text{(GPa)}$',
                     x_title='$G_{VRH} \\text{(GPa)}$',
                     colorbar_title='$\\nu$')
    pf.xy(('G_VRH', 'K_VRH'), labels='material_id', colors='poisson_ratio')
Example #12
0
def formatting_example(api_key, username):
    """
    Demonstrate common and advanced formatting features of PlotlyFig.

    PlotlyFig provides a set of arguments which make setting up good
    looking Plotly templates quick(er) and easy(er).

    Most formatting options can be set through the initializer of PlotlyFig.
    These options will remain the same for all figures producted, but you can
    change some common formatting options after instantitating a PlotlyFig
    object using set_arguments.

    Chart-specific formatting options can be passed to plotting methods.
    """

    if not api_key or not username:
        raise ValueError("Specify your Plotly api_key and username!")

    df = load_elastic_tensor()

    pf = PlotlyFig(df=df,
                   api_key=api_key,
                   username=username,
                   mode='online',
                   title='Comparison of Bulk Modulus and Shear Modulus',
                   x_title='Shear modulus (GPa)',
                   y_title='Bulk modulus (GPa)',
                   colorbar_title='Poisson Ratio',
                   fontfamily='Raleway',
                   fontscale=0.75,
                   fontcolor='#283747',
                   ticksize=30,
                   colorscale="Reds",
                   hovercolor='white',
                   hoverinfo='text',
                   bgcolor='#F4F6F6',
                   margins=110,
                   pad=10)

    pf.xy(('G_VRH', 'K_VRH'), labels='material_id', colors='poisson_ratio')


    # We can also use LaTeX if we use Plotly online/static
    pf.set_arguments(title="$\\text{Origin of Poisson Ratio } \\nu $",
                     y_title='$K_{VRH} \\text{(GPa)}$',
                     x_title='$G_{VRH} \\text{(GPa)}$',
                     colorbar_title='$\\nu$')
    pf.xy(('G_VRH', 'K_VRH'), labels='material_id', colors='poisson_ratio')
def plot_scatter_matrix():
    """
    A few different scatter matrix plots using elastic dataset in matminer.
    Returns:
        plotly plot in "offline" mode opened in the default browser.
    """
    df = load_elastic_tensor()
    pf = PlotlyFig(df)

    # basic matrix:
    pf.scatter_matrix(cols=['K_VRH', 'G_VRH', 'nsites', 'volume'])

    # with colorscale and labels:
    pf.scatter_matrix(cols=['K_VRH', 'G_VRH', 'nsites', 'volume'],
                      colors='nsites',
                      labels='material_id',
                      colorscale='Picnic')

    # with all the numerical columns included (note the change in sizes):
    pf = PlotlyFig(filename='scatter_matrix_elastic', fontscale=0.6)
    pf.scatter_matrix(df, marker_scale=0.6)
Example #14
0
def plot_modes(api_key, username):
    """
    Demonstrate PlotlyFig plotting modes and show the easiest way to make
    adjustments.

    Offline mode - Set "mode" to "offline"
    Create a local html file. Note that offline mode in plotly disables LaTeX
    and some fonts on some systems by default. For the full-featured Plotly
    experience, please use the Plotly online mode.

    Static mode - Set "mode" to "static"
    Creates a single image file. Use height and width to specify the size of the
    image desired. api_key and username are required for static plotting mode.

    Online mode - Set "mode" to "online"
    Opens the figure in the Plotly online module.

    Notebook mode - Set "mode" to "notebook"
    Opens the figure in a Jupyter/IPython notebook. Not shown here, seen
    matminer_examples repository.

    Return mode - Pass "return_plot=True" into any plotting method
    Returns the figure as a 'bare-bones' dictionary. This can then be edited and
    passed into 'create_plot' of PlotlyFig or used directly with plotly.

    """

    if not api_key or not username:
        raise ValueError("Specify your Plotly api_key and username!")

    df = load_elastic_tensor()

    # First lets set uo our figure generally.
    pf = PlotlyFig(df,
                   title='Elastic data',
                   mode='offline',
                   x_scale='log',
                   y_scale='log')

    # Lets plot offline (the default) first. An html file will be created.
    pf.xy([('poisson_ratio', 'elastic_anisotropy')], labels='formula')

    # Now lets plot again, but changing the filename and without opening.
    # We do this with the 'set_arguments' method.
    pf.set_arguments(show_offline_plot=False, filename="myplot.html")
    pf.xy([('poisson_ratio', 'elastic_anisotropy')], labels='formula')

    # Now lets create a static image.
    pf.set_arguments(mode='static',
                     api_key=api_key,
                     username=username,
                     filename="my_PlotlyFig_plot.jpeg")
    pf.xy([('poisson_ratio', 'elastic_anisotropy')], labels='formula')
    # You can change the size of the image with the 'height' and 'width'
    # arguments to set_arguments.

    # Now we will use the Plotly online interface.
    pf.set_arguments(mode='online')
    pf.xy([('poisson_ratio', 'elastic_anisotropy')], labels='formula')

    # Great! Lets get the JSON representation of the PlotlyFig template as a
    # python dictionary. We can do this without changing the plot mode. From
    # any plotting method, simply pass 'return_plot=True' to return the plot.
    fig = pf.xy([('poisson_ratio', 'elastic_anisotropy')],
                labels='formula',
                return_plot=True)
    print("Here's our returned figure!")
    pprint.pprint(fig)

    # Edit the figure and plot it with the current plot mode (online):
    fig['layout']['hoverlabel']['bgcolor'] = 'pink'
    fig['layout']['title'] = 'My Custom Elastic Data Figure'
    pf.create_plot(fig)
Example #15
0
    interp_params = get_energy_args(coeff_file, ibands=[vbm_idx+1, vbm_idx+2])
    # bsd['vb0'] = bs.bands[vbm_spin][vbm_idx] - vbm
    bsd['vb0'], _, _ = interpolate_bs(bsd['kpoints'], interp_params, iband=0,
                           method="boltztrap1", scissor=0.0, matrix=vrun.final_structure.lattice.matrix, n_jobs=-1)
    vbm = max(bsd['vb0'])
    bsd['vb0'] -= vbm

    # bsd['cb0'] = bs.bands[cbm_spin][cbm_idx] - vbm
    bsd['cb0'], _, _ = interpolate_bs(bsd['kpoints'], interp_params, iband=1,
                           method="boltztrap1", scissor=0.0, matrix=vrun.final_structure.lattice.matrix, n_jobs=-1)
    bsd['cb0'] -= vbm
    cbm = min(bsd['cb0'])

    bs_df = pd.DataFrame.from_dict(bsd)

    pf = PlotlyFig(bs_df, x_title='index', y_title='Energy (eV)',
                   filename='interpolated_line-mode')
    plt = pf.xy([(bs_df.index, 'vb0'), (bs_df.index, 'cb0')], labels='str_kpts', return_plot=True)

    extrema_data_x = []
    extrema_data_y = []
    extrema_data_labels = []

    initial_extrema_data_x = []
    initial_extrema_data_y = []
    initial_extrema_data_labels = []

    for iband, tp in enumerate(['p', 'n']):
        energies, _, _ = interpolate_bs(extrema[tp], interp_params, iband=iband,
                                          method="boltztrap1", scissor=0.0,
                                          matrix=vrun.final_structure.lattice.matrix,
                                          n_jobs=-1)
Example #16
0
def basic_bar():
    pf = PlotlyFig()
    pf.bar(x=['var a', 'var b', 'var c'], y=[1, 2, 3])
def basic_parallel_coordinates():
    df = load_dataset("elastic_tensor_2015")
    pf = PlotlyFig(df, title="Elastic tensor dataset", colorscale='Jet')
    pf.parallel_coordinates(colors='volume')
def basic_parallel_coordinates():
    df = load_elastic_tensor()
    pf = PlotlyFig(df, title="Elastic tensor dataset", colorscale='Jet')
    pf.parallel_coordinates(colors='volume')
Example #19
0
def retrieve_bs_boltztrap1(coeff_file, bs, ibands, matrix=None):
    interp_params = get_energy_args(coeff_file, ibands)
    pf = PlotlyFig(filename='Energy-bt1')
    plot_data = []
    v_data = []
    mass_data = []
    trace_names = []
    Eref = 0.0
    vels = {iband: [] for iband in ibands}
    sym_line_kpoints = []

    for i, iband in enumerate(ibands):
        sym_line_kpoints = [k.frac_coords for k in bs.kpoints]

        en, vel, masses = interpolate_bs(sym_line_kpoints,
                                         interp_params,
                                         iband=i,
                                         method="boltztrap1",
                                         scissor=0.0,
                                         matrix=matrix,
                                         n_jobs=-1)
        vel = np.linalg.norm(vel, axis=1)
        masses = [mass.trace() / 3.0 for mass in masses]
        if i == 0:
            Eref = max(en)
        en = [E - Eref for E in en]
        plot_data.append((list(range(len(en))), en))
        v_data.append((en, vel))
        mass_data.append((en, masses))
        trace_names.append('band {}'.format(iband))

    pf.xy(plot_data, names=[n for n in trace_names], labels=[sym_line_kpoints])
    pf2 = PlotlyFig(filename='Velocity-bt1')
    pf2.xy(v_data, names=[n for n in trace_names])
    pf3 = PlotlyFig(filename='mass-bt1')
    pf3.xy(mass_data, names=[n for n in trace_names])
Example #20
0
def simple_violin():
    df = load_elastic_tensor()
    pf = PlotlyFig(df, title="Distribution of Elastic Constant Averages",
                   colorscale='Reds')
    pf.violin(cols=['K_Reuss', 'K_Voigt', 'G_Reuss', 'G_Voigt'],
              use_colorscale=True)
print('test score:')
print(model.score(X_test, y_test))

analysis = Analytics(model,
                     X_train,
                     y_train,
                     X_test,
                     y_test,
                     mode,
                     target=target,
                     features=df.drop(target, axis=1).columns,
                     test_samples_index=X_test.index,
                     random_state=RS)

x = list(analysis.get_feature_importance(sort=False).values())
y = model.feature_importances_
lr = linregress(x, y)
xreg = np.linspace(0.0, round(max(x), 2), num=2)
yreg = lr.intercept + xreg * lr.slope

print('correlation, r={}'.format(lr.rvalue))
print('p-value, p={}'.format(lr.pvalue))

pf = PlotlyFig(
    title='Comparison of feature importances in predicting expt. gap',
    x_title='Analytics.feature_importance (Variance Sensitivity Analysis)',
    y_title='RandomForestRegressor.feature_importances_')
pf.xy([(x, y), (xreg, yreg)],
      labels=analysis.features,
      modes=['markers', 'line'],
      showlegends=False)
Example #22
0
def retrieve_bs_boltztrap2(vrun, bs, ibands, matrix=None):
    pf = PlotlyFig(filename='Energy-bt2')
    sym_line_kpoints = [k.frac_coords for k in bs.kpoints]
    bz_data = PymatgenLoader(vrun)
    equivalences = sphere.get_equivalences(atoms=bz_data.atoms,
                                           nkpt=len(bz_data.kpoints) * 5,
                                           magmom=None)
    lattvec = bz_data.get_lattvec()
    coeffs = fite.fitde3D(bz_data, equivalences)
    kpts = np.array(sym_line_kpoints)
    interp_params = (equivalences, lattvec, coeffs)
    plot_data = []
    v_data = []
    names = []
    mass_data = []
    eref = 0.0
    for ith, iband in enumerate(ibands):
        en, vel, masses = interpolate_bs(kpts,
                                         interp_params,
                                         iband=iband,
                                         method="boltztrap2",
                                         matrix=matrix)
        # method = "boltztrap2", matrix = lattvec * 0.529177)
        if ith == 0:
            eref = np.max(en)
        en -= eref
        plot_data.append((list(range(len(en))), en))
        v_data.append((en, np.linalg.norm(vel, axis=1)))
        mass_data.append((en, [mass.trace() / 3.0 for mass in masses]))
        names.append('band {}'.format(iband + 1))
    pf.xy(plot_data, names=[n for n in names])
    pf2 = PlotlyFig(filename='Velocity-bt2')
    pf2.xy(v_data, names=[n for n in names])
    pf3 = PlotlyFig(filename='mass-bt2')
    pf3.xy(mass_data, names=[n for n in names])
Example #23
0
def plot_modes(api_key, username):
    """
    Demonstrate PlotlyFig plotting modes and show the easiest way to make
    adjustments.

    Offline mode - Set "mode" to "offline"
    Create a local html file. Note that offline mode in plotly disables LaTeX
    and some fonts on some systems by default. For the full-featured Plotly
    experience, please use the Plotly online mode.

    Static mode - Set "mode" to "static"
    Creates a single image file. Use height and width to specify the size of the
    image desired. api_key and username are required for static plotting mode.

    Online mode - Set "mode" to "online"
    Opens the figure in the Plotly online module.

    Notebook mode - Set "mode" to "notebook"
    Opens the figure in a Jupyter/IPython notebook. Not shown here, seen
    matminer_examples repository.

    Return mode - Pass "return_plot=True" into any plotting method
    Returns the figure as a 'bare-bones' dictionary. This can then be edited and
    passed into 'create_plot' of PlotlyFig or used directly with plotly.

    """

    if not api_key or not username:
        raise ValueError("Specify your Plotly api_key and username!")

    df = load_elastic_tensor()

    # First lets set uo our figure generally.
    pf = PlotlyFig(df, title='Elastic data', mode='offline', x_scale='log',
                   y_scale='log')

    # Lets plot offline (the default) first. An html file will be created.
    pf.xy([('poisson_ratio', 'elastic_anisotropy')], labels='formula')

    # Now lets plot again, but changing the filename and without opening.
    # We do this with the 'set_arguments' method.
    pf.set_arguments(show_offline_plot=False, filename="myplot.html")
    pf.xy([('poisson_ratio', 'elastic_anisotropy')], labels='formula')

    # Now lets create a static image.
    pf.set_arguments(mode='static',
                     api_key=api_key,
                     username=username,
                     filename="my_PlotlyFig_plot.jpeg")
    pf.xy([('poisson_ratio', 'elastic_anisotropy')], labels='formula')
    # You can change the size of the image with the 'height' and 'width'
    # arguments to set_arguments.

    # Now we will use the Plotly online interface.
    pf.set_arguments(mode='online')
    pf.xy([('poisson_ratio', 'elastic_anisotropy')], labels='formula')

    # Great! Lets get the JSON representation of the PlotlyFig template as a
    # python dictionary. We can do this without changing the plot mode. From
    # any plotting method, simply pass 'return_plot=True' to return the plot.
    fig = pf.xy([('poisson_ratio', 'elastic_anisotropy')], labels='formula',
                return_plot=True)
    print("Here's our returned figure!")
    pprint.pprint(fig)

    # Edit the figure and plot it with the current plot mode (online):
    fig['layout']['hoverlabel']['bgcolor'] = 'pink'
    fig['layout']['title'] = 'My Custom Elastic Data Figure'
    pf.create_plot(fig)