sort facets of an altair plot bases on group statistic

  • Last Update :
  • Techknowledgy :

You can use an EncodingSortField on the facet encoding; e.g.

p = alt.Chart(df).mark_point().encode(
   y = 'value',
   x = 'Date Time',
   color = 'variable',
   facet = alt.Facet('variable',
      sort = alt.EncodingSortField('value', op = 'mean', order = 'descending')
   )
)

# set some aditional properties
p.properties(width = 230, height = 150, columns = 3).resolve_scale()

Suggestion : 2

I would like to change the order of the anycodings_sorting facets of an Altair chart based based on anycodings_sorting some groups statistics such as mean, sigma, anycodings_sorting etc. ,I read some posts that indicate sorting on x anycodings_sorting and y is possible, but this is case where I anycodings_sorting would like to sort the faces themselves.,I would like the sort order to be largest anycodings_sorting mean to smallest mean:,In some cases, the ordering function may be anycodings_sorting more complex, such as the delta between two anycodings_sorting moving averages, slope of an EWMA, etc, anycodings_sorting so I would also like to be able to "pass" in anycodings_sorting the order if possible.

Here's the testable case code:

import pandas as pd
import numpy as np
import altair as alt

alt.renderers.enable('notebook')

# make some data to test
N = 500
df = pd.DataFrame({
   'Date Time': pd.date_range('2019-06-19', periods = N, freq = 'H'),
   'A': np.random.normal(6, 1, N),
   'B': np.random.normal(5, 1, N),
   'C': np.random.normal(7, 1, N),
   'D': np.random.normal(8, 1, N)
}).melt('Date Time')

# render the chart using facets
p = alt.Chart(df).mark_point().encode(
   facet = 'variable',
   y = 'value',
   x = 'Date Time',
   color = 'variable',
)

# set some aditional properties
p.properties(width = 230, height = 150, columns = 3).resolve_scale()

I would like the sort order to be largest anycodings_sorting mean to smallest mean:

var_order = df.groupby('variable').mean().sort_values('variable', ascending = False).index.values
var_order

which produces:

array(['D', 'C', 'B', 'A'], dtype = object)

You can use an EncodingSortField on the anycodings_python facet encoding; e.g.

p = alt.Chart(df).mark_point().encode(
   y = 'value',
   x = 'Date Time',
   color = 'variable',
   facet = alt.Facet('variable',
      sort = alt.EncodingSortField('value', op = 'mean', order = 'descending')
   )
)

# set some aditional properties
p.properties(width = 230, height = 150, columns = 3).resolve_scale()

Suggestion : 3

Sort Facets Of An Altair Plot Bases On Group Statistic,I would like to change the order of the facets of an Altair chart based based on some groups statistics such as mean, sigma, etc. , Faceting is a great technique to simplify a complex visualization. Faceting splits a single plot into multiple smaller plots containing subset of data corresponding to a group. This tutorial we will see an example of how to facet a scatter plot with Altair in Python. , Now, that we have a dataset containing three columns, where we want to compare the highest score (values) of two players (series) across different formats (categories). We can plot a group chart by calling the alt.Chart () method present inside Altair library.


import pandas as pd
import numpy as np
import altair as alt alt.renderers.enable('notebook') # make some data to test N = 500 df = pd.DataFrame({
   'Date Time': pd.date_range('2019-06-19', periods = N, freq = 'H'),
   'A': np.random.normal(6, 1, N),
   'B': np.random.normal(5, 1, N),
   'C': np.random.normal(7, 1, N),
   'D': np.random.normal(8, 1, N)
}).melt('Date Time') # render the chart using facets p = alt.Chart(df).mark_point().encode(facet = 'variable', y = 'value', x = 'Date Time', color = 'variable', ) # set some aditional properties p.properties(width = 230, height = 150, columns = 3).resolve_scale()

Suggestion : 4

The IPython notebook is a browser-based interactive data analysis tool that can combine narrative, code, graphics, HTML elements, and much more into a single executable document (see Chapter 1).,Plotting interactively within an IPython notebook can be done with the %matplotlib command, and works in a similar way to the IPython shell. In the IPython notebook, you also have the option of embedding graphics directly in the notebook, with two possible options:,Again, note that we can accomplish this type of rotation interactively by clicking and dragging when using one of Matplotlib’s interactive backends.,It can be very convenient to use Matplotlib interactively within an IPython shell (see Chapter 1). IPython is built to work well with Matplotlib if you specify Matplotlib mode. To enable this mode, you can use the %matplotlib magic command after starting ipython:

Just as we use the np shorthand for NumPy and the pd shorthand for Pandas, we will use some standard shorthands for Matplotlib imports:

In[1]: import matplotlib as mpl
import matplotlib.pyplot as plt

We will use the plt.style directive to choose appropriate aesthetic styles for our figures. Here we will set the classic style, which ensures that the plots we create use the classic Matplotlib style:

In[2]: plt.style.use('classic')

So, for example, you may have a file called myplot.py containing the following:

#-- -- -- - file: myplot.py-- -- --
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)

plt.plot(x, np.sin(x))
plt.plot(x, np.cos(x))

plt.show()

You can then run this script from the command-line prompt, which will result in a window opening with your figure displayed:

$ python myplot.py

It can be very convenient to use Matplotlib interactively within an IPython shell (see Chapter 1). IPython is built to work well with Matplotlib if you specify Matplotlib mode. To enable this mode, you can use the %matplotlib magic command after starting ipython:

In[1]: % matplotlib
Using matplotlib backend: TkAgg

In[2]: import matplotlib.pyplot as plt

For this book, we will generally opt for %matplotlib inline:

In[3]: % matplotlib inline

After you run this command (it needs to be done only once per kernel/session), any cell within the notebook that creates a plot will embed a PNG image of the resulting graphic (Figure 4-1):

In[4]: import numpy as np
x = np.linspace(0, 10, 100)

fig = plt.figure()
plt.plot(x, np.sin(x), '-')
plt.plot(x, np.cos(x), '--');

One nice feature of Matplotlib is the ability to save figures in a wide variety of formats. You can save a figure using the savefig() command. For example, to save the previous figure as a PNG file, you can run this:

In[5]: fig.savefig('my_figure.png')

We now have a file called my_figure.png in the current working directory:

In[6]: !ls - lh my_figure.png
In[6]: !ls -lh my_figure.png
-rw - r--r--1 jakevdp staff 16 K Aug 11 10: 59 my_figure.png

In savefig(), the file format is inferred from the extension of the given filename. Depending on what backends you have installed, many different file formats are available. You can find the list of supported file types for your system by using the following method of the figure canvas object:

In[8]: fig.canvas.get_supported_filetypes()
In[8]: fig.canvas.get_supported_filetypes()
Out[8]: {
   'eps': 'Encapsulated Postscript',
   'jpeg': 'Joint Photographic Experts Group',
   'jpg': 'Joint Photographic Experts Group',
   'pdf': 'Portable Document Format',
   'pgf': 'PGF code for LaTeX',
   'png': 'Portable Network Graphics',
   'ps': 'Postscript',
   'raw': 'Raw RGBA bitmap',
   'rgba': 'Raw RGBA bitmap',
   'svg': 'Scalable Vector Graphics',
   'svgz': 'Scalable Vector Graphics',
   'tif': 'Tagged Image File Format',
   'tiff': 'Tagged Image File Format'
}