Archie  Clayton

Archie Clayton

1665114443

Data Visualization Charts and Prepare with AWS Quicksight

Learn how to create Data Visualization charts and Prepare with AWS Quicksight. Learn Data Science and Analytics with AWS Quicksight

In this course you would learn to create Visualization Charts and Data Preparation in AWS Quicksight. It is a powerful Business Intelligence tool that can be used perform a wide range of tasks such as:

Importing Dataset form multiple sources such as direct upload, S3 bucket, Redshift and other databases in multiple formats such as csv, xls and more.

Data Cleaning- by removing unwanted rows, columns or fields, from the dataset based on a given condition by using Filters and Excluded lists

Data Preparation- by adding custom columns or fields by either using a mathematical function or by customizing some existing fields using various function such as concat, ceil and much more

Changing Field type among String, Integer, Decimal, Country, State, Date, Time and other formats

Visualization Charts- by taking multiple fields and arranging them in Dimensions and Measures.

Analytics Dashboard- by creating various visualization charts and combining them on a single page to create a BI report or Analytics dashboard. It could be used to find insights from the dataset and identify trends, outliers and critical information

Conditional Formatting- by customizing the visual charts in terms of colors, data values, date range, value range and others

You will learning these data skills in this course. Data Science involves various phases from data extraction, data preparation, data cleaning, modelling to data visualization and analysis. With AWS Quicksight, we can perform most of these Data science tasks and you will learn about some of them in the step wise manner. Firstly, you will learn to create a analytics dashboard right from the dataset. You will learn to import a dataset on AWS. Next you will learn to create some of the basic visualization charts such as bar, pie, treemap and other charts. After getting familiar with the Quicksight interface, you will learn to prepare your dataset so that only useful and relevant information in passed to the visualization phase. You will learn to create Filters, Excluded lists and Calculated fields where you could add, remove or modify any of the data element.

After learning data preparation, you will learn to create some of the advanced visualization charts such as Map chart, Pivot table and Sankey chart. Using various charts you can create a analytics dashboard to find useful insights from the dataset.

What you’ll learn

  •        You would be able to create various kinds of Visualization charts using AWS Quicksight
  •        You could create charts such as Pie, Bar, Sankey, Treemap and Pivot table
  •        You could visually find insights from the dataset and perform analysis to find useful information
  •        You could also prepare your data before visualization by removing unwanted rows, columns and cells based on given conditions
  •        You could create Filters and Calculated fields to perform data cleaning and preparation

Are there any course requirements or prerequisites?

  •        Before taking this course, if you are familiar with AWS (Amazon Web Services) cloud computing platform, it would be useful
  •        Basic idea about data preparation such as with Excel or any BI editors

Who this course is for:

  •        Anyone who is curious to learn Data Science on AWS cloud computing platform using Quicksight
  •        Anyone interested in creating Data Visualization Charts such as Sankey, Map, etc
  •        Students and Professionals interested in learning AWS Quicksight
  •        Anyone interested in Data Analysis and Business Intelligence


#datavisualization #aws

Data Visualization Charts and Prepare with AWS Quicksight
Lawrence  Lesch

Lawrence Lesch

1664529480

Pix-plot: A WebGL Viewer for UMAP Or TSNE-clustered Images

PixPlot

This repository contains code that can be used to visualize tens of thousands of images in a two-dimensional projection within which similar images are clustered together. The image analysis uses Tensorflow's Inception bindings, and the visualization layer uses a custom WebGL viewer.

See the change log for recent updates.

App preview

Dependencies

To install the Python dependencies, we recommend you install Anaconda and then create a conda environment with a Python 3.7 runtime:

conda create --name=3.7 python=3.7
source activate 3.7

Then you can install the dependencies by running:

pip uninstall pixplot
pip install https://github.com/yaledhlab/pix-plot/archive/master.zip

Please note that you will need to use Python 3.6 or Python 3.7 to install and use this package. The HTML viewer also requires a WebGL-enabled browser.

Quickstart

If you have a WebGL-enabled browser and a directory full of images to process, you can prepare the data for the viewer by installing the dependencies above then running:

pixplot --images "path/to/images/*.jpg"

To see the results of this process, you can start a web server by running:

# for python 3.x
python -m http.server 5000

# for python 2.x
python -m SimpleHTTPServer 5000

The visualization will then be available at http://localhost:5000/output.

Sample Data

To acquire some sample data with which to build a plot, feel free to use some data prepared by Yale's DHLab:

pip install image_datasets

Then in a Python script:

import image_datasets
image_datasets.oslomini.download()

The .download() command will make a directory named datasets in your current working directory. That datasets directory will contain a subdirectory named 'oslomini', which contains a directory of images and another directory with a CSV file of image metadata. Using that data, we can next build a plot:

pixplot --images "datasets/oslomini/images/*" --metadata "datasets/oslomini/metadata/metadata.csv"

Creating Massive Plots

If you need to plot more than 100,000 images but don't have an expensive graphics card with which to visualize huge WebGL displays, you might want to specify a smaller "cell_size" parameter when building your plot. The "cell_size" argument controls how large each image is in the atlas files; smaller values require fewer textures to be rendered, which decreases the GPU RAM required to view a plot:

pixplot --images "path/to/images/*.jpg" --cell_size 10

Controlling UMAP Layout

The UMAP algorithm is particularly sensitive to three hyperparemeters:

--min_dist: determines the minimum distance between points in the embedding
--n_neighbors: determines the tradeoff between local and global clusters
--metric: determines the distance metric to use when positioning points

UMAP's creator, Leland McInnes, has written up a helpful overview of these hyperparameters. To specify the value for one or more of these hyperparameters when building a plot, one may use the flags above, e.g.:

pixplot --images "path/to/images/*.jpg" --n_neighbors 2

Curating Automatic Hotspots

PixPlot uses Hierarchical density-based spatial clustering of applications with noise, a refinement of the earlier DBSCAN algorithm, to find hotspots in the visualization. You may be interested in consulting this explanation of how HDBSCAN works.

Adding Metadata

If you have metadata associated with each of your images, you can pass in that metadata when running the data processing script. Doing so will allow the PixPlot viewer to display the metadata associated with an image when a user clicks on that image.

To specify the metadata for your image collection, you can add --metadata=path/to/metadata.csv to the command you use to call the processing script. For example, you might specify:

pixplot --images "path/to/images/*.jpg" --metadata "path/to/metadata.csv"

Metadata should be in a comma-separated value file, should contain one row for each input image, and should contain headers specifying the column order. Here is a sample metadata file:

filenamecategorytagsdescriptionpermalinkYear
bees.jpgyellowa|b|cbees' kneeshttps://...1776
cats.jpgdangerousb|c|dcats' pajamashttps://...1972

The following column labels are accepted:

ColumnDescription
filenamethe filename of the image
categorya categorical label for the image
tagsa pipe-delimited list of categorical tags for the image
descriptiona plaintext description of the image's contents
permalinka link to the image hosted on another domain
yeara year timestamp for the image (should be an integer)
labela categorical label used for supervised UMAP projection
latthe latitudinal position of the image
lngthe longitudinal position of the image

IIIF Images

If you would like to process images that are hosted on a IIIF server, you can specify a newline-delimited list of IIIF image manifests as the --images argument. For example, the following could be saved as manifest.txt:

https://manifests.britishart.yale.edu/manifest/40005
https://manifests.britishart.yale.edu/manifest/40006
https://manifests.britishart.yale.edu/manifest/40007
https://manifests.britishart.yale.edu/manifest/40008
https://manifests.britishart.yale.edu/manifest/40009

One could then specify these images as input by running pixplot --images manifest.txt --n_clusters 2

Demonstrations (Developed with PixPlot 2.0 codebase)

LinkImage CountCollection InfoBrowse ImagesDownload for PixPlot
NewsPlot: 1910-191224,026George Grantham Bain CollectionNews in the 1910sImages, Metadata
Bildefelt i Oslo31,097oslobilderAdvanced search, 1860-1924Images, Metadata

Acknowledgements

The DHLab would like to thank Cyril Diagne and Nicolas Barradeau, lead developers of the spectacular Google Arts Experiments TSNE viewer, for generously sharing ideas on optimization techniques used in this viewer, and Lillianna Marie for naming this viewer PixPlot.

Download Details:

Author: YaleDHLab
Source Code: https://github.com/YaleDHLab/pix-plot 
License: MIT license

#javascript #webgl #datavisualization 

Pix-plot: A WebGL Viewer for UMAP Or TSNE-clustered Images
Lawrence  Lesch

Lawrence Lesch

1664517300

Genome-spy: A GPU-accelerated toolkit & Visualization Grammar

GenomeSpy

GenomeSpy is a visualization toolkit for genomic (and other) data. It has a Vega-Lite inspired visualization grammar and high-performance, WebGL-powered graphics rendering.

The software is still work in progress. Documentation and examples for the current version can be found at https://genomespy.app/

Teaser

Monorepo

GenomeSpy is split into several packages, two of which are the most important:

Core

The core library provides the visualization grammar and a WebGL-powered rendering engine.

App

The app builds upon the core, extending the visualization grammar with support for faceting multiple (up to thousands of) patient samples. It provides a user interface for interactive analysis of the samples, which can be filtered, sorted, and grouped flexibly. A session handling with provenance, url hashes, and bookmarks is included.

Contributing

Bootstrapping and running

  1. git clone git@github.com:genome-spy/genome-spy.git
  2. cd genome-spy
  3. npm install (use npm7!)
  4. npm start (starts the App)

The packages/core/examples directory contains some random view specification that can be accessed through urls like http://localhost:8080/?spec=examples/first.json.

The packages/core/private/ directory is in .gitignore and served by the development server: http://localhost:8080/?spec=private/foo.json. Use it for experiments that should not go into version control.

If you want to use or develop the core library, launch a single-page app using: npm -w @genome-spy/core run dev

Download Details:

Author: Genome-spy
Source Code: https://github.com/genome-spy/genome-spy 
License: BSD-2-Clause license

#javascript #visualization #webgl #datavisualization 

Genome-spy: A GPU-accelerated toolkit & Visualization Grammar
Royce  Reinger

Royce Reinger

1664015900

5 Favorite Data Visualization Library for Rust

In today's post we will learn about 5 Favorite Data Visualization Library for Rust.

What is Data Visualization?

Data visualization is the graphical representation of information and data. By using visual elements like charts, graphs, and maps, data visualization tools provide an accessible way to see and understand trends, outliers, and patterns in data. Additionally, it provides an excellent way for employees or business owners to present data to non-technical audiences without confusion.

In the world of Big Data, data visualization tools and technologies are essential to analyze massive amounts of information and make data-driven decisions.

Table of contents:

  • Djduque/pgfplots [pgfplots] - A Rust library to generate publication-quality figures. 
  • Igiagkiozis/plotly - Plotly for Rust.
  • Milliams/plotlib - Data plotting library for Rust.
  • Plotters - A rust drawing library for high quality data plotting for both WASM and native, statically and realtimely. 
  • Saresend/gust - A small charting/visualization tool and partial vega implementation for Rust.

1 - Djduque/pgfplots [pgfplots]:

A Rust library to generate publication-quality figures. This crate is a PGFPlots code generator, and provides utilities to create, customize, and compile high-quality plots.

Usage

Add the following to your Cargo.toml file:

[dependencies]
pgfplots = { version = "0.4", features = ["inclusive"] }

Plotting a quadratic function is as simple as:

use pgfplots::axis::plot::Plot2D;

let mut plot = Plot2D::new();
plot.coordinates = (-100..100)
    .into_iter()
    .map(|i| (f64::from(i), f64::from(i*i)).into())
    .collect();

plot.show()?;

Examples

A more extensive list of examples and their source code is available in the examples/ directory (runnable with cargo run --all-features --example example_name).

[code][code][code]

Features

Inclusive: Allow users to process the LaTeX code that generates figures without relying on any externally installed software, configuration, or resource files. This is achieved by including the tectonic crate as a dependency.

If you already have a LaTeX distribution installed in your system, it is recommended to process the LaTeX code directly. The tectonic crate pulls in a lot of dependencies, which significantly increase compilation and processing times. Plotting a quadratic function is still very simple:

 use pgfplots::axis::plot::Plot2D;
 use std::process::{Command, Stdio};

 let mut plot = Plot2D::new();
 plot.coordinates = (-100..100)
 	.into_iter()
 	.map(|i| (f64::from(i), f64::from(i*i)).into())
 	.collect();

 let argument = plot.standalone_string().replace('\n', "").replace('\t', "");
 Command::new("pdflatex")
 	.stdout(Stdio::null())
 	.stderr(Stdio::null())
 	.arg("-interaction=batchmode")
 	.arg("-halt-on-error")
 	.arg("-jobname=figure")
 	.arg(argument)
 	.status()
 	.expect("Error: unable to run pdflatex");

View on Github

2 - Igiagkiozis/plotly:

Plotly for Rust.

A plotting library for Rust powered by Plotly.js.

Usage

Add this to your Cargo.toml:

[dependencies]
plotly = "0.8.0"

Crate Feature Flags

The following feature flags are available:

  • kaleido
    • Optional, compatible with Rust stable.
    • Adds plot save functionality to the following formats: png, jpeg, webp, svg, pdf and eps.
    • Requires some additional configuration, see plotly_kaleido.
  • plotly_ndarray
    • Optional, compatible with Rust stable.
    • Adds support for creating plots directly using ndarray types.
  • wasm
    • Optional, compatible with Rust stable.
    • Disables OS-specific functions, therefore allowing compilation in WASM environments. Note that examples won't compile when this feature is enabled, as they require OS-specific functions.

Saving to png, jpeg, webp, svg, pdf and eps formats can be made available by enabling the kaleido feature:

[dependencies]
plotly = { version = "0.8.0", features = ["kaleido"] }

For further details please see plotly_kaleido.

View on Github

3 - Milliams/plotlib:

Data plotting library for Rust.

plotlib is a generic data visualisation and plotting library for Rust. It is currently in the very early stages of development.

It can currently produce:

  • histograms
  • scatter plots
  • line graphs from data or from function definitions
  • box plots
  • bar charts

rendering them as either SVG or plain text.

The API is still very much in flux and is subject to change.

For example, code like:

use plotlib::page::Page;
use plotlib::repr::Plot;
use plotlib::view::ContinuousView;
use plotlib::style::{PointMarker, PointStyle};

fn main() {
    // Scatter plots expect a list of pairs
    let data1 = vec![
        (-3.0, 2.3),
        (-1.6, 5.3),
        (0.3, 0.7),
        (4.3, -1.4),
        (6.4, 4.3),
        (8.5, 3.7),
    ];

    // We create our scatter plot from the data
    let s1: Plot = Plot::new(data1).point_style(
        PointStyle::new()
            .marker(PointMarker::Square) // setting the marker to be a square
            .colour("#DD3355"),
    ); // and a custom colour

    // We can plot multiple data sets in the same view
    let data2 = vec![(-1.4, 2.5), (7.2, -0.3)];
    let s2: Plot = Plot::new(data2).point_style(
        PointStyle::new() // uses the default marker
            .colour("#35C788"),
    ); // and a different colour

    // The 'view' describes what set of data is drawn
    let v = ContinuousView::new()
        .add(s1)
        .add(s2)
        .x_range(-5., 10.)
        .y_range(-2., 6.)
        .x_label("Some varying variable")
        .y_label("The response of something");

    // A page with a single view is then saved to an SVG file
    Page::single(&v).save("scatter.svg").unwrap();
}

View on Github

4 - Plotters:

A rust drawing library for high quality data plotting for both WASM and native, statically and realtimely.

Plotters is drawing library designed for rendering figures, plots, and charts, in pure rust. Plotters supports various types of back-ends, including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.

  • A new Plotters Developer's Guide is working in progress. The preview version is available at here.
  • To try Plotters with interactive Jupyter notebook, or view here for the static HTML version.
  • To view the WASM example, go to this link
  • Currently we have all the internal code ready for console plotting, but a console based backend is still not ready. See this example for how to plotting on Console with a customized backend.
  • Plotters now moved all backend code to sperate repositories, check FAQ list for details
  • Some interesting demo projects are available, feel free to try them out.

Dependencies

Ubuntu Linux

sudo apt install pkg-config libfreetype6-dev libfontconfig1-dev

Quick Start

To use Plotters, you can simply add Plotters into your Cargo.toml

[dependencies]
plotters = "0.3.1"

And the following code draws a quadratic function. src/main.rs,

use plotters::prelude::*;
fn main() -> Result<(), Box<dyn std::error::Error>> {
    let root = BitMapBackend::new("plotters-doc-data/0.png", (640, 480)).into_drawing_area();
    root.fill(&WHITE)?;
    let mut chart = ChartBuilder::on(&root)
        .caption("y=x^2", ("sans-serif", 50).into_font())
        .margin(5)
        .x_label_area_size(30)
        .y_label_area_size(30)
        .build_cartesian_2d(-1f32..1f32, -0.1f32..1f32)?;

    chart.configure_mesh().draw()?;

    chart
        .draw_series(LineSeries::new(
            (-50..=50).map(|x| x as f32 / 50.0).map(|x| (x, x * x)),
            &RED,
        ))?
        .label("y = x^2")
        .legend(|(x, y)| PathElement::new(vec![(x, y), (x + 20, y)], &RED));

    chart
        .configure_series_labels()
        .background_style(&WHITE.mix(0.8))
        .border_style(&BLACK)
        .draw()?;

    root.present()?;

    Ok(())
}

Demo Projects

To learn how to use Plotters in different scenarios by checking out the following demo projects:

View on Github

5 - Saresend/gust:

A small charting/visualization tool and partial vega implementation for Rust.

What is Gust

Gust is a small charting crate to make it really easy to build simple interactive data visualizations in rust. It also serves as a partial Vega implementation that will (hopefully) become more complete over time.


Gust allows you to render the actual visualizations themselves using D3.js, (meaning they're interactive!) as well as providing the flexibility to directly render the underlying JSON specification for Vega.

Currently Implementations

Currently, Gust supports only 3 charts so far:

  1. Bar Charts
  2. Stacked Bar Charts
  3. Line Charts

More will be coming soon! If you're interested in contributing your own, just make a pull request. Cheers!

Why did you do this in rust?

Installation

gust = "0.1.4"

Samples and Sample Usage

    use backend::bar_chart::BarChart;
    use frontend::write::render_graph;

Sample Bar Chart

     let mut b = BarChart::new();
        let v = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"];
        for i in 0..10 {
            b.add_data(v[i].to_string(), (i * i * i) as i32);
        }
        render_graph(&b, FileType::HTML).unwrap();

Result: gust_build/html/bar_chart.html

bar chart

Stacked Bar Chart example

use backend::stacked_bar_chart::StackedBarChart;

let mut b = StackedBarChart::new();
        for i in 0..10 {
            b.add_data(i, i * i, 1);
            b.add_data(i, i + i, 0);
        }
        render_graph(&b, FileType::HTML).unwrap();

View on Github

Thank you for following this article.

Related videos:

Visualizing memory layout of Rust's data types

#rust #datavisualization 

5 Favorite Data Visualization Library for Rust
Reid  Rohan

Reid Rohan

1663020540

10 Best Libraries for Data Visualization tools For The Web

In today's post we will learn about 10 Best Libraries for Data visualization tools for the web.

What is Data Visualization?

Data visualization is the process of graphical representation of data in the form of geographic maps, charts, sparklines, infographics, heat maps, or statistical graphs. 

Data presented through visual elements is easy to understand and analyze, enabling the effective extraction of actionable insights from the data. Relevant stakeholders can then use the findings to make more efficient real-time decisions.

Data visualization tools, incorporating support for streaming data, AI integration, embeddability, collaboration, interactive exploration, and self-service capabilities, facilitate the visual representation of data. 

Table of contents:

  • D3 - A JavaScript visualization library for HTML and SVG.
  • Metrics-graphics - A library optimized for concise, principled data graphics and layouts.
  • Three.js - JavaScript 3D library.
  • Chart.js - Simple HTML5 Charts using the <canvas> tag.
  • Paper.js - The Swiss Army Knife of Vector Graphics Scripting – Scriptographer ported to JavaScript and the browser, using HTML5 Canvas.
  • Fabric.js - JavaScript Canvas Library, SVG-to-Canvas (& canvas-to-SVG) Parser.
  • Peity - Progressive bar, line and pie charts.
  • Raphael - JavaScript Vector Library.
  • Echarts - Enterprise Charts.
  • Two.js - A renderer agnostic two-dimensional drawing api for the web.

1 - D3: A JavaScript visualization library for HTML and SVG.

D3 (or D3.js) is a JavaScript library for visualizing data using web standards. D3 helps you bring data to life using SVG, Canvas and HTML. D3 combines powerful visualization and interaction techniques with a data-driven approach to DOM manipulation, giving you the full capabilities of modern browsers and the freedom to design the right visual interface for your data.

Installing

If you use npm, npm install d3. You can also download the latest release on GitHub. For vanilla HTML in modern browsers, import D3 from Skypack:

<script type="module">

import * as d3 from "https://cdn.skypack.dev/d3@7";

const div = d3.selectAll("div");

</script>

For legacy environments, you can load D3’s UMD bundle from an npm-based CDN such as jsDelivr; a d3 global is exported:

<script src="https://cdn.jsdelivr.net/npm/d3@7"></script>
<script>

const div = d3.selectAll("div");

</script>

You can also use the standalone D3 microlibraries. For example, d3-selection:

<script type="module">

import {selectAll} from "https://cdn.skypack.dev/d3-selection@3";

const div = selectAll("div");

</script>

D3 is written using ES2015 modules. Create a custom bundle using Rollup, Webpack, or your preferred bundler. To import D3 into an ES2015 application, either import specific symbols from specific D3 modules:

import {scaleLinear} from "d3-scale";

Or import everything into a namespace (here, d3):

import * as d3 from "d3";

Or using dynamic import:

const d3 = await import("d3");

You can also import individual modules and combine them into a d3 object using Object.assign:

const d3 = await Promise.all([
  import("d3-format"),
  import("d3-geo"),
  import("d3-geo-projection")
]).then(d3 => Object.assign({}, ...d3));

View on Github

2 - Metrics-graphics: A library optimized for concise, principled data graphics and layouts.

MetricsGraphics is a library built for visualizing and laying out time-series data. At around 15kB (gzipped), it provides a simple way to produce common types of graphics in a principled and consistent way. The library currently supports line charts, scatterplots and histograms, as well as features like rug plots.

Example

All you need to do is add an entry node to your document:

<div id="chart"></div>

Then, use the id to mount the chart:

import LineChart from 'metrics-graphics'

new LineChart({
  data, // some array of data objects
  width: 600,
  height: 200,
  target: '#chart',
  area: true,
  xAccessor: 'date',
  yAccessor: 'value'
})

That's it!

Sample Screenshot

The raw data for this example can be found here

View on Github

3 - Three.js: JavaScript 3D library.

JavaScript 3D library

The aim of the project is to create an easy to use, lightweight, cross-browser, general purpose 3D library. The current builds only include a WebGL renderer but WebGPU (experimental), SVG and CSS3D renderers are also available in the examples.

Usage

This code creates a scene, a camera, and a geometric cube, and it adds the cube to the scene. It then creates a WebGL renderer for the scene and camera, and it adds that viewport to the document.body element. Finally, it animates the cube within the scene for the camera.

import * as THREE from 'three';

// init

const camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 10 );
camera.position.z = 1;

const scene = new THREE.Scene();

const geometry = new THREE.BoxGeometry( 0.2, 0.2, 0.2 );
const material = new THREE.MeshNormalMaterial();

const mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );

const renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setAnimationLoop( animation );
document.body.appendChild( renderer.domElement );

// animation

function animation( time ) {

	mesh.rotation.x = time / 2000;
	mesh.rotation.y = time / 1000;

	renderer.render( scene, camera );

}

If everything went well, you should see this.

Cloning this repository

Cloning the repo with all its history results in a ~2 GB download. If you don't need the whole history you can use the depth parameter to significantly reduce download size.

git clone --depth=1 https://github.com/mrdoob/three.js.git

View on Github

4 - Chart.js: Simple HTML5 Charts using the <canvas> tag.

Installation

You can get the latest version of Chart.js from npm , the GitHub releases , or use a Chart.js CDN . Detailed installation instructions can be found on the installation page.

If you're using a front-end framework (e.g., React, Angular, or Vue), please check available integrations .

Creating a Chart

It's easy to get started with Chart.js. All that's required is the script included in your page along with a single <canvas> node to render the chart.

In this example, we create a bar chart for a single dataset and render that in our page. You can see all the ways to use Chart.js in the usage documentation.

<canvas id="myChart" width="400" height="400"></canvas>
<script>
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            y: {
                beginAtZero: true
            }
        }
    }
});
</script>

View on Github

5 - Paper.js: The Swiss Army Knife of Vector Graphics Scripting – Scriptographer ported to JavaScript and the browser, using HTML5 Canvas.

Installing Paper.js

The recommended way to install and maintain Paper.js as a dependency in your project is through the Node.js Package Manager (NPM) for browsers, Node.js or Electron.

If NPM is already installed, simply type one of these commands in your project folder:

npm install paper

Upon execution, you will find a paper folder inside the project's node_modules folder.

For more information on how to install Node.js and NPM, read the chapter Installing Node.js and NPM.

Which Version to Use

The various distributions come with two different pre-build versions of Paper.js, in minified and normal variants:

  • paper-full.js – The full version for the browser, including PaperScript support and Acorn.js
  • paper-core.js – The core version for the browser, without PaperScript support nor Acorn.js. You can use this to shave off some bytes and compilation time when working with JavaScript directly.

Installing Node.js and NPM

Node.js comes with the Node Package Manager (NPM). There are many tutorials explaining the different ways to install Node.js on different platforms. It is generally not recommended to install Node.js through OS-supplied package managers, as the its development cycles move fast and these versions are often out-of-date.

On macOS, Homebrew is a good option if one version of Node.js that is kept up to date with brew upgrade is enough:
https://treehouse.github.io/installation-guides/mac/node-mac.html

NVM can be used instead to install and maintain multiple versions of Node.js on the same platform, as often required by different projects:
https://nodesource.com/blog/installing-node-js-tutorial-using-nvm-on-mac-os-x-and-ubuntu/

Homebrew is recommended on macOS also if you intend to install Paper.js with rendering to the Canvas on Node.js, as described in the next paragraph.

For Linux, see https://nodejs.org/download/ to locate 32-bit and 64-bit Node.js binaries as well as sources, or use NVM, as described in the paragraph above.

View on Github

6 - Fabric.js: JavaScript Canvas Library, SVG-to-Canvas (& canvas-to-SVG) Parser.

FabricJS.com is a simple and powerful Javascript HTML5 canvas library. It is also an SVG-to-canvas parser.

Quick Start

$ npm install fabric --save

After this, you can import fabric like so:

const fabric = require("fabric").fabric;

Or you can use this instead if your build pipeline supports ES6 imports:

import { fabric } from "fabric";

NOTE: If you are using Fabric.js in a Node.js script, you will depend on node-canvas. node-canvas is an HTML canvas replacement that works on top of native libraries. Please follow the instructions to get it up and running.

NOTE: es6 imports won't work in browser or with bundlers which expect es6 module like vite. Use commonjs syntax instead.

Usage

Plain HTML

<canvas id="canvas" width="300" height="300"></canvas>

<!-- Get latest version: https://cdnjs.com/libraries/fabric.js -->
<script src="lib/fabric.js"></script> 
<script>
    var canvas = new fabric.Canvas('canvas');

    var rect = new fabric.Rect({
        top : 100,
        left : 100,
        width : 60,
        height : 70,
        fill : 'red'
    });
    canvas.add(rect);
</script>

ReactJS

import React, {useEffect, useRef} from 'react'
import {fabric} from 'fabric'

const FabricJSCanvas = () => {
  const canvasEl = useRef(null)
  useEffect(() => {
    const options = { ... };
    const canvas = new fabric.Canvas(canvasEl.current, options);
    // make the fabric.Canvas instance available to your app
    updateCanvasContext(canvas);
    return () => {
      updateCanvasContext(null);
      canvas.dispose()
    }
  }, []);
  
  return (<canvas width="300" height="300" ref={canvasEl}/>)
});
export default FabricJSCanvas;

NOTE: Fabric.js requires a window object.

View on Github

7 - Peity: Progressive bar, line and pie charts.

Peity (sounds like deity) is a jQuery plugin that converts an element's content into a mini <svg> pie, donut, line or bar chart.

Basic Usage

HTML

<span class="pie">3/5</span>
<span class="donut">5,2,3</span>
<span class="line">3,5,1,6,2</span>
<span class="bar">2,5,3,6,2,1</span>

JavaScript (jQuery)

$(".pie").peity("pie");
$(".donut").peity("donut");
$(".line").peity("line");
$(".bar").peity("bar");

Docs

More detailed usage can be found at benpickles.github.io/peity.

View on Github

8 - Raphael: JavaScript Vector Library.

Quickstart guide

You need to have NPM installed to build the library.

  • git clone https://github.com/DmitryBaranovskiy/raphael.git
  • yarn install --frozen-lockfile
  • yarn build-all

To run tests you need to run npx bower install open dev/test/index.html in your browser, there's no automated way right now.

Dependencies

Distributable

All files are UMD compliant.

You can use:

  • raphael.min.js (includes eve and it's minified)
  • raphael.js (includes eve and it's not minified)
  • raphael.no-deps.js (doesn't include eve it's not minified)
  • raphael.no-deps.min.js (doesn't include eve it's minified)

Where to start

Check Raphael-boilerplate to see examples of loading.

Raphael can be loaded in a script tag or with AMD:

define([ "path/to/raphael" ], function( Raphael ) {
  console.log( Raphael );
});

View on Github

9 - Echarts: Enterprise Charts.

Apache ECharts is a free, powerful charting and visualization library offering an easy way of adding intuitive, interactive, and highly customizable charts to your commercial products. It is written in pure JavaScript and based on zrender, which is a whole new lightweight canvas library.

Build

Build echarts source code:

Execute the instructions in the root directory of the echarts: (Node.js is required)

# Install the dependencies from NPM:
npm install

# Rebuild source code immediately in watch mode when changing the source code.
npm run dev

# Check correctness of TypeScript code.
npm run checktype

# If intending to build and get all types of the "production" files:
npm run release

Then the "production" files are generated in the dist directory.

Contribution

If you wish to debug locally or make pull requests, please refer to the contributing document.

View on Github

10 - Two.js: A renderer agnostic two-dimensional drawing api for the web.

A two-dimensional drawing api meant for modern browsers. It is renderer agnostic enabling the same api to render in multiple contexts: webgl, canvas2d, and svg.

Usage

Download the latest minified library and include it in your html.

<script src="js/two.min.js"></script>

It can also be installed via npm, Node Package Manager:

npm install --save two.js

Alternatively see how to build the library yourself.

Here is boilerplate html in order to draw a spinning rectangle in two.js:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <script src="js/two.min.js"></script>
  </head>
  <body>
    <script>
      var two = new Two({
        fullscreen: true,
        autostart: true
      }).appendTo(document.body);
      var rect = two.makeRectangle(two.width / 2, two.height / 2, 50 ,50);
      two.bind('update', function() {
        rect.rotation += 0.001;
      });
    </script>
  </body>
</html>

Custom Build

Two.js uses nodejs in order to build source files. You'll first want to install that. Once installed open up a terminal and head to the repository folder:

cd ~/path-to-repo/two.js
npm install

This will give you a number of libraries that the development of Two.js relies on. If for instance you only use the SvgRenderer then you can really cut down on the file size by excluding the other renderers. To do this, modify /utils/build.js to only add the files you'd like. Then run:

node ./utils/build

And the resulting /build/two.js and /build/two.min.js will be updated to your specification.

View on Github

Thank you for following this article.

Related videos:

Data Visualization For Data Science | Data Visualization Projects

#javascript #datavisualization 

10 Best Libraries for Data Visualization tools For The Web
Nat  Grady

Nat Grady

1661538420

Billboarder: R Htmlwidget for billboard.js

billboarder

Htmlwidget for billboard.js

Overview

This package allow you to use billboard.js, a re-usable easy interface JavaScript chart library, based on D3 v4+.

A proxy method is implemented to smoothly update charts in shiny applications, see below for details.

Installation :

Install from CRAN with:

install.packages("billboarder")

Install development version grom GitHub with:

# install.packages("remotes")
remotes::install_github("dreamRs/billboarder")

For interactive examples & documentation, see pkgdown site : https://dreamrs.github.io/billboarder/index.html

Bar / column charts

Simple bar chart :

library("billboarder")

# data
data("prod_par_filiere")

# a bar chart !
billboarder() %>%
  bb_barchart(data = prod_par_filiere[, c("annee", "prod_hydraulique")], color = "#102246") %>%
  bb_y_grid(show = TRUE) %>%
  bb_y_axis(tick = list(format = suffix("TWh")),
            label = list(text = "production (in terawatt-hours)", position = "outer-top")) %>% 
  bb_legend(show = FALSE) %>% 
  bb_labs(title = "French hydraulic production",
          caption = "Data source: RTE (https://opendata.rte-france.com)")

Multiple categories bar chart :

library("billboarder")

# data
data("prod_par_filiere")

# dodge bar chart !
billboarder() %>%
  bb_barchart(
    data = prod_par_filiere[, c("annee", "prod_hydraulique", "prod_eolien", "prod_solaire")]
  ) %>%
  bb_data(
    names = list(prod_hydraulique = "Hydraulic", prod_eolien = "Wind", prod_solaire = "Solar")
  ) %>% 
  bb_y_grid(show = TRUE) %>%
  bb_y_axis(tick = list(format = suffix("TWh")),
            label = list(text = "production (in terawatt-hours)", position = "outer-top")) %>% 
  bb_legend(position = "inset", inset = list(anchor = "top-right")) %>% 
  bb_labs(title = "Renewable energy production",
          caption = "Data source: RTE (https://opendata.rte-france.com)")

Stacked bar charts :

library("billboarder")

# data
data("prod_par_filiere")

# stacked bar chart !
billboarder() %>%
  bb_barchart(
    data = prod_par_filiere[, c("annee", "prod_hydraulique", "prod_eolien", "prod_solaire")], 
    stacked = TRUE
  ) %>%
  bb_data(
    names = list(prod_hydraulique = "Hydraulic", prod_eolien = "Wind", prod_solaire = "Solar"), 
    labels = TRUE
  ) %>% 
  bb_colors_manual(
    "prod_eolien" = "#41AB5D", "prod_hydraulique" = "#4292C6", "prod_solaire" = "#FEB24C"
  ) %>%
  bb_y_grid(show = TRUE) %>%
  bb_y_axis(tick = list(format = suffix("TWh")),
            label = list(text = "production (in terawatt-hours)", position = "outer-top")) %>% 
  bb_legend(position = "right") %>% 
  bb_labs(title = "Renewable energy production",
          caption = "Data source: RTE (https://opendata.rte-france.com)")

Scatter plot

Classic :

library(billboarder)
library(palmerpenguins)
billboarder() %>% 
  bb_scatterplot(data = penguins, x = "bill_length_mm", y = "flipper_length_mm", group = "species") %>% 
  bb_axis(x = list(tick = list(fit = FALSE))) %>% 
  bb_point(r = 8)

You can make a bubble chart using size aes :

billboarder() %>% 
  bb_scatterplot(
    data = penguins, 
    mapping = bbaes(
      bill_length_mm, flipper_length_mm, group = species,
      size = scales::rescale(body_mass_g, c(1, 100))
    )
  ) %>% 
  bb_bubble(maxR = 25) %>% 
  bb_x_axis(tick = list(fit = FALSE))

Pie / Donut charts

library("billboarder")

# data
data("prod_par_filiere")
nuclear2016 <- data.frame(
  sources = c("Nuclear", "Other"),
  production = c(
    prod_par_filiere$prod_nucleaire[prod_par_filiere$annee == "2016"],
    prod_par_filiere$prod_total[prod_par_filiere$annee == "2016"] -
      prod_par_filiere$prod_nucleaire[prod_par_filiere$annee == "2016"]
  )
)

# pie chart !
billboarder() %>% 
  bb_piechart(data = nuclear2016) %>% 
  bb_labs(title = "Share of nuclear power in France in 2016",
          caption = "Data source: RTE (https://opendata.rte-france.com)")

Lines charts

Time serie with Date (and a subchart)

library("billboarder")

# data
data("equilibre_mensuel")

# line chart
billboarder() %>% 
  bb_linechart(
    data = equilibre_mensuel[, c("date", "consommation", "production")], 
    type = "spline"
  ) %>% 
  bb_x_axis(tick = list(format = "%Y-%m", fit = FALSE)) %>% 
  bb_x_grid(show = TRUE) %>% 
  bb_y_grid(show = TRUE) %>% 
  bb_colors_manual("consommation" = "firebrick", "production" = "forestgreen") %>% 
  bb_legend(position = "right") %>% 
  bb_subchart(show = TRUE, size = list(height = 30)) %>% 
  bb_labs(title = "Monthly electricity consumption and production in France (2007 - 2017)",
          y = "In megawatt (MW)",
          caption = "Data source: RTE (https://opendata.rte-france.com)")

lines-subchart.gif

Zoom by dragging

billboarder() %>% 
  bb_linechart(
    data = equilibre_mensuel[, c("date", "consommation", "production")], 
    type = "spline"
  ) %>% 
  bb_x_axis(tick = list(format = "%Y-%m", fit = FALSE)) %>% 
  bb_x_grid(show = TRUE) %>% 
  bb_y_grid(show = TRUE) %>% 
  bb_colors_manual("consommation" = "firebrick", "production" = "forestgreen") %>% 
  bb_legend(position = "right") %>% 
  bb_zoom(
    enabled = list(type = "drag"),
    resetButton = list(text = "Unzoom")
  ) %>% 
  bb_labs(title = "Monthly electricity consumption and production in France (2007 - 2017)",
          y = "In megawatt (MW)",
          caption = "Data source: RTE (https://opendata.rte-france.com)")

lines-zoom-drag.gif

Time serie with POSIXct (and regions)

library("billboarder")

# data
data("cdc_prod_filiere")

# Retrieve sunrise and and sunset data with `suncalc`
library("suncalc")
sun <- getSunlightTimes(date = as.Date("2017-06-12"), lat = 48.86, lon = 2.34, tz = "CET")


# line chart
billboarder() %>% 
  bb_linechart(data = cdc_prod_filiere[, c("date_heure", "prod_solaire")]) %>% 
  bb_x_axis(tick = list(format = "%H:%M", fit = FALSE)) %>% 
  bb_y_axis(min = 0, padding = 0) %>% 
  bb_regions(
    list(
      start = as.numeric(cdc_prod_filiere$date_heure[1]) * 1000,
      end = as.numeric(sun$sunrise)*1000
    ), 
    list(
      start = as.numeric(sun$sunset) * 1000, 
      end = as.numeric(cdc_prod_filiere$date_heure[48]) * 1000
    )
  ) %>% 
  bb_x_grid(
    lines = list(
      list(value = as.numeric(sun$sunrise)*1000, text = "sunrise"),
      list(value = as.numeric(sun$sunset)*1000, text = "sunset")
    )
  ) %>% 
  bb_labs(title = "Solar production (2017-06-12)",
          y = "In megawatt (MW)",
          caption = "Data source: RTE (https://opendata.rte-france.com)")

Stacked area chart

library("billboarder")

# data
data("cdc_prod_filiere")

# area chart !
billboarder() %>% 
  bb_linechart(
    data = cdc_prod_filiere[, c("date_heure", "prod_eolien", "prod_hydraulique", "prod_solaire")], 
    type = "area"
  ) %>% 
  bb_data(
    groups = list(list("prod_eolien", "prod_hydraulique", "prod_solaire")),
    names = list("prod_eolien" = "Wind", "prod_hydraulique" = "Hydraulic", "prod_solaire" = "Solar")
  ) %>% 
  bb_legend(position = "inset", inset = list(anchor = "top-right")) %>% 
  bb_colors_manual(
    "prod_eolien" = "#238443", "prod_hydraulique" = "#225EA8", "prod_solaire" = "#FEB24C", 
    opacity = 0.8
  ) %>% 
  bb_y_axis(min = 0, padding = 0) %>% 
  bb_labs(title = "Renewable energy production (2017-06-12)",
          y = "In megawatt (MW)",
          caption = "Data source: RTE (https://opendata.rte-france.com)")

Line range

# Generate data
dat <- data.frame(
  date = seq.Date(Sys.Date(), length.out = 20, by = "day"),
  y1 = round(rnorm(20, 100, 15)),
  y2 = round(rnorm(20, 100, 15))
)
dat$ymin1 <- dat$y1 - 5
dat$ymax1 <- dat$y1 + 5

dat$ymin2 <- dat$y2 - sample(3:15, 20, TRUE)
dat$ymax2 <- dat$y2 + sample(3:15, 20, TRUE)


# Make chart : use ymin & ymax aes for range
billboarder(data = dat) %>% 
  bb_linechart(
    mapping = bbaes(x = date, y = y1, ymin = ymin1, ymax = ymax1),
    type = "area-line-range"
  ) %>% 
  bb_linechart(
    mapping = bbaes(x = date, y = y2, ymin = ymin2, ymax = ymax2), 
    type = "area-spline-range"
  ) %>% 
  bb_y_axis(min = 50)

Histogram & density

billboarder() %>%
  bb_histogram(data = rnorm(1e5), binwidth = 0.25) %>%
  bb_colors_manual()

With a grouping variable :

# Generate some data
dat <- data.frame(
  sample = c(rnorm(n = 1e4, mean = 1), rnorm(n = 1e4, mean = 2)),
  group = rep(c("A", "B"), each = 1e4), stringsAsFactors = FALSE
)
# Mean by groups
samples_mean <- tapply(dat$sample, dat$group, mean)
# histogram !
billboarder() %>%
  bb_histogram(data = dat, x = "sample", group = "group", binwidth = 0.25) %>%
  bb_x_grid(
    lines = list(
      list(value = unname(samples_mean['A']), text = "mean of sample A"),
      list(value = unname(samples_mean['B']), text = "mean of sample B")
    )
  )

Density plot with the same data :

billboarder() %>%
  bb_densityplot(data = dat, x = "sample", group = "group") %>%
  bb_x_grid(
    lines = list(
      list(value = unname(samples_mean['A']), text = "mean of sample A"),
      list(value = unname(samples_mean['B']), text = "mean of sample B")
    )
  )

Shiny interaction

Some events will trigger Shiny's inputs in application, such as click. Inputs id associated with billboarder charts use this pattern :

input$CHARTID_EVENT

Look at this example, chart id is mybbchart so you retrieve click with input$mybbchart_click :

library("shiny")
library("billboarder")

# data
data("prod_par_filiere")
prod_par_filiere_l <- reshape2::melt(data = prod_par_filiere)
prod_par_filiere_l <- prod_par_filiere_l[
  with(prod_par_filiere_l, annee == "2016" & variable != "prod_total"), 2:3
]
prod_par_filiere_l <- prod_par_filiere_l[order(prod_par_filiere_l$value), ]


# app
ui <- fluidPage(
  billboarderOutput(outputId = "mybbchart"),
  br(),
  verbatimTextOutput(outputId = "click")
)

server <- function(input, output, session) {
  
  output$mybbchart <- renderBillboarder({
    billboarder() %>%
      bb_barchart(data = prod_par_filiere_l) %>% 
      bb_y_grid(show = TRUE) %>% 
      bb_legend(show = FALSE) %>%
      bb_x_axis(categories = prod_par_filiere_l$variable, fit = FALSE) %>% 
      bb_labs(title = "French electricity generation by branch in 2016",
              y = "production (in terawatt-hours)",
              caption = "Data source: RTE (https://opendata.rte-france.com)")
  })
  
  output$click <- renderPrint({
    cat("# input$mybbchart_click$category", "\n")
    input$mybbchart_click$category
  })
  
}

shinyApp(ui = ui, server = server)

Proxy

You can modify existing charts with function billboarderProxy : billboarder_proxy.gif

To see examples, run :

library("billboarder")
proxy_example("bar")
proxy_example("line")
proxy_example("pie")
proxy_example("gauge")

Raw API

If you wish, you can build graphs using a list syntax :

data(economics, package = "ggplot2")

# Construct a list in JSON format
params <- list(
  data = list(
    x = "x",
    json = list(
      x = economics$date,
      y = economics$psavert
    ),
    type = "spline"
  ),
  legend = list(show = FALSE),
  point = list(show = FALSE),
  axis = list(
    x = list(
      type = "timeseries",
      tick = list(
        count = 20,
        fit = TRUE,
        format = "%e %b %y"
      )
    ),
    y = list(
      label = list(
        text = "Personal savings rate"
      ),
      tick = list(
        format = htmlwidgets::JS("function(x) {return x + '%';}")
      )
    )
  )
)

# Pass the list as parameter
billboarder(params)

Download Details:

Author: DreamRs
Source Code: https://github.com/dreamRs/billboarder 
License: Unknown, MIT licenses found

#r #datavisualization  

Billboarder: R Htmlwidget for billboard.js
Nat  Grady

Nat Grady

1661347320

A Shiny Framework for Workflow Management & Data Visualization

systemPipeShiny 

systemPipeShiny(SPS) a Shiny-based R/Bioconductor package that extends the widely used systemPipeR workflow environment with data visualization and a versatile graphical user interface. SPS can work as a general framework to build custom web apps on data analysis and visualization. Besides, SPS provides many developer tools that are distributed as separate packages.

design

Demos

SPS has provided a variety of options to change how it work. Here are some examples.

Type and linkoption changednotes
Default full installationSee installationfull app, may take longer (~15s) to load
Minimum installationSee installationno modules installed
Login enabledlogin_screen = TRUE; login_theme = "empty"no modules installed
Login and login themeslogin_screen = TRUE; login_theme = "random"no modules installed
App admin pageadmin_page = TRUEuse the link or simply add "?admin" to the end of URL of any demos

For the login required demos, the app account name is "user" password "user".

For the admin login, account name "admin", password "admin".

Please DO NOT delete or change password when you are trying the admin features. Although shinyapps.io will reset the app once a while, this will affect other people who are viewing the demo simultaneously.

Rstudio Cloud

There is an Rstudio Cloud project instance that you can also play with. You need to create a free new account. Two Bioconductor related modules - workflow & RNAseq are not installed. They require more than 1GB RAM to install and to run which is beyond the limit of a free account.

Documents

To see all the details of SPS, read the user manual on our website.

Installation

SPS is under heavy development. We recommend to install the develop version (most recent) for the latest features.

Full

if (!requireNamespace("BiocManager", quietly=TRUE))
    install.packages("BiocManager")
BiocManager::install("systemPipeShiny", dependencies=TRUE)

This will install all required packages including suggested packages that are required by the core modules. Be aware, it will take quite some time if you are installing on Linux where only source installation is available. Windows and Mac binary installations will be much faster.

Minimum

To install the package, please use the BiocManager::install command:

if (!requireNamespace("BiocManager", quietly=TRUE))
    install.packages("BiocManager")
BiocManager::install("systemPipeShiny")

By the minimum installation, all the 3 core modules are not installed. You can still start the app, and when you start the app and click on these modules, it will tell to enable these modules, what packages to install and what command you need to run. Just follow the instructions. Install as you need.

Most recent

To obtain the most recent updates immediately, one can install it directly from GitHub as follow:

if (!requireNamespace("remotes", quietly=TRUE))
    install.packages("remotes")
remotes::install("systemPipeR/systemPipeShiny", dependencies=TRUE)

Similarly, remotes::install("systemPipeR/systemPipeShiny") for the minimum develop version.

Linux

If you are on Linux, you may also need the following system dependencies before installing SPS. Different distributions may have different commands, but the following commands are examples for Ubuntu:

sudo apt-get install -y libicu-dev
sudo apt-get install -y pandoc
sudo apt-get install -y zlib1g-dev
sudo apt-get install -y libcurl4-openssl-dev
sudo apt-get install -y libssl-dev      
sudo apt-get install -y make

Quick start

This is a basic example which shows how to use systempipeShiny package:

## Imports the library
library(systemPipeShiny)
## Creates the project directory
spsInit()

By default, a project folder is created and named as SPS_+DATE. This project folder provides all the necessary files to launch the application. If you are using Rstudio, global.R file will be opened automatically and this is the only file you may need to make custom changes if there is any.

Click the green "Run App" button in Rstudio if you are on the global.R file or run following in console to start the app.

## Launching the interface
shiny::runApp()

options

Change some of the options listed in global.R will change how the app behave, for example, modules to load, title, logo, whether to apply user authentication, and more ...

Other packages in systemPipeShiny

PackageDescriptionDocumentsFunction referenceDemo
systemPipeShinySPS main packagewebsitelinkdemo
spsCompsSPS UI and server componentswebsitelinkdemo
drawerSPS interactive image editing toolwebsitelinkdemo
spsUtilSPS utility functionswebsitelinkNA

Screenshots of SPS

Full app

sps

Loading screens

loading screens

Workflow module

WF

Workflow Execution

WF run

RNASeq module

RNASeq module

RNASeq module

Canvas

canvas

Admin

Admin

Admin

Admin

Debugging

Debugging

Contact & contributions

Please use https://github.com/systemPipeR/systemPipeShiny/issues for reporting bugs, issues or for suggesting new features to be implemented.

We'd love to hear from all users and developers. Submit your pull request if you have new thoughts or improvements.

Download Details:

Author: systemPipeR
Source Code: https://github.com/systemPipeR/systemPipeShiny 

#r #datavisualization #workflow 

A Shiny Framework for Workflow Management & Data Visualization
Nat  Grady

Nat Grady

1661052720

Esquisse: RStudio Add-in to Make Plots interactively with Ggplot2

esquisse

The purpose of this add-in is to let you explore your data quickly to extract the information they hold. You can create visualization with {ggplot2}, filter data with {dplyr} and retrieve generated code.   

This addin allows you to interactively explore your data by visualizing it with the ggplot2 package. It allows you to draw bar plots, curves, scatter plots, histograms, boxplot and sf objects, then export the graph or retrieve the code to reproduce the graph.

nstallation

Install from CRAN with :

install.packages("esquisse")

Or install development version from GitHub :

remotes::install_github("dreamRs/esquisse")

Then launch the addin via the RStudio menu or with esquisse::esquisser().

esquisse addin

esquisse::esquisser()
# or with your data:
esquisse::esquisser(palmerpenguins::penguins)

esquisse.gif

Above gif was made with ❤️ by @mfanny and cannot be removed, but in the meantime {esquisse} has evolved, the latest version now looks like:

Internationalization

Currently you can use {esquisse} in the following language: english (default), french ("fr"), macedonian ("mk"), albanian ("al"). Activate with:

library(esquisse)
set_i18n("fr")
esquisser()

If you want another language to be supported, you can submit a Pull Request to add a CSV file like the one used for french (file is located in inst/i18n folder in the package, you can see it here on GitHub).

See {datamods} vignette for more on this topic.

See online documentation : https://dreamrs.github.io/esquisse/index.html

If you find bugs, please open an issue

Download Details:

Author: DreamRs
Source Code: https://github.com/dreamRs/esquisse 
License: View license

#r #visualization #datavisualization 

Esquisse: RStudio Add-in to Make Plots interactively with Ggplot2

Temporal.jl: Time Series Implementation for The Julia Language

Temporal

This package provides a flexible & efficient time series class, TS, for the Julia programming language. While still early in development, the overarching goal is for the class to be able to slice & dice data with the rapid prototyping speed of R's xts and Python's pandas packages, while retaining the performance one expects from Julia.

See the documentation for a more in-depth look at the package and some of the pain points it may solve when doing technical research with time series data.

Below is a brief teaser with a minimal use case illustrating a small subset of features. This example also makes use of the Indicators.jl package, which provides a series of financial market technical analysis indicators with wrappers for the Temporal.TS type. Visualization is offered through the Plots.jl package, which Temporal leverages through RecipesBase.jl.

using Temporal, Plots, Indicators

crude = quandl("CHRIS/CME_CL1")
gasoline = quandl("CHRIS/CME_RB1")

prices = [crude["2012/2019", :Settle] gasoline["2012/2019", :Settle]]
prices.fields = [:Crude, :Gasoline]
prices = dropnan(prices)
daily_returns = diff(log(prices))
cumulative_returns = cumprod(1 + daily_returns)

spread = cumulative_returns[:,1] - cumulative_returns[:,2]
spread = [spread sma(spread, n=200)]
spread.fields = Symbol.(["Spread", "SMA (200)"])

gr()
ℓ = @layout[ a{0.7h}; b{0.3h} ]
plot(cumulative_returns, c=[:black :purple], layout=ℓ, subplot=1)
plot!(spread, c=[:blue :orange], layout=ℓ, subplot=2)

alt text

Download Details:

Author: Dysonance
Source Code: https://github.com/dysonance/Temporal.jl 
License: View license

#julia #datavisualization #finance 

Temporal.jl: Time Series Implementation for The Julia Language
Nat  Grady

Nat Grady

1660108440

Wordcloud2: R interface to Wordcloud for Data Visualization

wordcloud2

R interface to wordcloud for data visualization. Timdream's wordcloud2.js is used in this package.

Original description

Installation

devtools::install_github("lchiffon/wordcloud2")

knitr and shiny is support in wordcloud2 package.

Example

library(wordcloud2)
wordcloud2(demoFreq, size = 1,shape = 'star')

1

wordcloud2(demoFreq, size = 2, minRotation = -pi/2, maxRotation = -pi/2)

1

wordcloud2(demoFreq, size = 2, minRotation = -pi/6, maxRotation = -pi/6,
  rotateRatio = 1)

1

Chinese version

## Sys.setlocale("LC_CTYPE","eng")
wordcloud2(demoFreqC, size = 2, fontFamily = "微软雅黑",
           color = "random-light", backgroundColor = "grey")

1

Example of successfully deploying interactivate clickable wordcloud with special shape on R-shiny

Thanks JacobXPX's contribution to this feature:

Thanks AdamSpannbauer for pointing out the issues.

Additional features are added or modified:

hover information display are fixed, refering AdeelK93's previous work, thanks!

multiple wordclouds which seperatedly click are supported.

clickedWordInputId is changed to be automatically generated by: paste0(outputId, "_clicked_word")).

See sample below for more details:

library(shiny)
library(wordcloud2)
shinyApp(
  ui=shinyUI(fluidPage(
    #using default clicked word input id
    wordcloud2Output("my_wc", width = "50%", height = "400px"),
    #using custom clicked word input id
    wordcloud2Output("my_wc2", width = "50%", height = "400px"),
    
    verbatimTextOutput("print"),
    verbatimTextOutput("print2")
  )),
  server=shinyServer(function(input,output,session){
    
    figPath = system.file("examples/a.png",package = "wordcloud2")
    
    output$my_wc  = renderWordcloud2(wordcloud2(data = demoFreq, figPath = figPath, size = 0.4,color = "blue"))
    output$my_wc2 = renderWordcloud2(wordcloud2(demoFreq))
    
    #using default clicked word input id
    output$print  = renderPrint(input$my_wc_clicked_word)
    #using custom clicked word input id
    output$print2 = renderPrint(input$my_wc2_clicked_word)
  })
)

run the above code and click refresh, it will work.

1

contributors

Download Details:

Author: Lchiffon
Source Code: https://github.com/Lchiffon/wordcloud2 

#r #datavisualization 

Wordcloud2: R interface to Wordcloud for Data Visualization
Nat  Grady

Nat Grady

1660081920

Plotly.R: an interactive Graphing Library for R

An R package for creating interactive web graphics via the open source JavaScript graphing library plotly.js.

Installation

Install from CRAN:

install.packages("plotly")

Or install the latest development version (on GitHub) via {remotes}:

remotes::install_github("plotly/plotly")

Getting started

Web-based ggplot2 graphics

If you use ggplot2, ggplotly() converts your static plots to an interactive web-based version!

library(plotly)
g <- ggplot(faithful, aes(x = eruptions, y = waiting)) +
  stat_density_2d(aes(fill = ..level..), geom = "polygon") + 
  xlim(1, 6) + ylim(40, 100)
ggplotly(g)

<https://i.imgur.com/G1rSArP.gifv>

By default, ggplotly() tries to replicate the static ggplot2 version exactly (before any interaction occurs), but sometimes you need greater control over the interactive behavior. The ggplotly() function itself has some convenient “high-level” arguments, such as dynamicTicks, which tells plotly.js to dynamically recompute axes, when appropriate. The style() function also comes in handy for modifying the underlying trace attributes (e.g. hoveron) used to generate the plot:

gg <- ggplotly(g, dynamicTicks = "y")
style(gg, hoveron = "points", hoverinfo = "x+y+text", hoverlabel = list(bgcolor = "white"))

<https://i.imgur.com/qRvLgea.gifv>

Moreover, since ggplotly() returns a plotly object, you can apply essentially any function from the R package on that object. Some useful ones include layout() (for customizing the layout), add_traces() (and its higher-level add_*() siblings, for example add_polygons(), for adding new traces/data), subplot() (for combining multiple plotly objects), and plotly_json() (for inspecting the underlying JSON sent to plotly.js).

The ggplotly() function will also respect some “unofficial” ggplot2 aesthetics, namely text (for customizing the tooltip), frame (for creating animations), and ids (for ensuring sensible smooth transitions).

Using plotly without ggplot2

The plot_ly() function provides a more direct interface to plotly.js so you can leverage more specialized chart types (e.g., parallel coordinates or maps) or even some visualization that the ggplot2 API won’t ever support (e.g., surface, mesh, trisurf, etc).

plot_ly(z = ~volcano, type = "surface")

<https://plot.ly/~brnvg/1134>

Learn more

To learn more about special features that the plotly R package provides (e.g., client-side linking, shiny integration, editing and generating static images, custom events in JavaScript, and more), see https://plotly-r.com. You may already be familiar with existing plotly documentation (e.g., https://plotly.com/r/), which is essentially a language-agnostic how-to guide for learning plotly.js, whereas https://plotly-r.com is meant to be more wholistic tutorial written by and for the R user. The package itself ships with a number of demos (list them by running demo(package = "plotly")) and shiny/rmarkdown examples (list them by running plotly_example("shiny") or plotly_example("rmd")). Carson also keeps numerous slide decks with useful examples and concepts.

Contributing

Please read through our contributing guidelines. Included are directions for opening issues, asking questions, contributing changes to plotly, and our code of conduct.


Download Details:

Author: Plotly
Source Code: https://github.com/plotly/plotly.R 
License: Unknown, MIT licenses found

#r #webgl #datavisualization #plotly 

Plotly.R: an interactive Graphing Library for R

Seaborn.jl: Julia Wrapper for Seaborn

Seaborn

A Julia wrapper around the Seaborn data visualization library:

Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics.

For a brief introduction to the ideas behind the library, you can read the introductory notes or the paper. Visit the installation page to see how you can download the package and get started with it. You can browse the example gallery to see some of the things that you can do with seaborn, and then check out the tutorial or API reference to find out how.

To see the code or report a bug, please visit the GitHub repository. General support questions are most at home on stackoverflow or discourse, which have dedicated channels for seaborn.

Gallery Gallery Gallery Gallery Gallery Gallery

Installation and usage

This Julia wrapper exposes all of the functions in the Seaborn API.

You need to have a Python distribution installed with the seaborn Python package. If you do not already have it, run pip install seaborn form the command line.

Download Details: 

Author: JuliaPy
Source Code: https://github.com/JuliaPy/Seaborn.jl 
License: View license

#julia #wrapper #datavisualization 

Seaborn.jl: Julia Wrapper for Seaborn
Nat  Grady

Nat Grady

1659943277

Waffle: Make Waffle (square Pie) Charts in R

waffle

Create Waffle Chart Visualizations

Description

Square pie charts (a.k.a. waffle charts) can be used to communicate parts of a whole for categorical quantities. To emulate the percentage view of a pie chart, a 10x10 grid should be used with each square representing 1% of the total. Modern uses of waffle charts do not necessarily adhere to this rule and can be created with a grid of any rectangular shape. Best practices suggest keeping the number of categories small, just as should be done when creating pie charts. Tools are provided to create waffle charts as well as stitch them together, and to use glyphs for making isotype pictograms.

It uses ggplot2 and returns a ggplot2 object.

What’s Inside the Tin

The following functions are implemented:

  • waffle: Make waffle (square pie) charts
  • draw_key_pictogram: Legend builder for pictograms
  • fa_grep: Search Font Awesome glyph names for a pattern
  • fa_list: List all Font Awesome glyphs
  • geom_pictogram: Pictogram Geom
  • geom_waffle: Waffle (Square pie chart) Geom
  • install_fa_fonts: Install Font Awesome 5 Fonts
  • iron: Veritical, left-aligned layout for waffle plots
  • scale_label_pictogram: Used with geom_pictogram() to map Font Awesome fonts to labels
  • theme_enhance_waffle: Waffle chart theme cruft remover that can be used with any other theme

Installation

install.packages("waffle", repos = "https://cinc.rud.is")
# or
devtools::install_git("https://git.rud.is/hrbrmstr/waffle.git")
# or
devtools::install_git("https://git.sr.ht/~hrbrmstr/waffle")
# or
devtools::install_gitlab("hrbrmstr/waffle")
# or
devtools::install_bitbucket("hrbrmstr/waffle")
# or
devtools::install_github("hrbrmstr/waffle")

Usage

library(waffle)
library(magrittr)
library(hrbrthemes)
library(ggplot2)
library(dplyr)
library(waffle)

# current verison
packageVersion("waffle")
## [1] '1.0.1'

Some new bits up first

data.frame(
  parts = factor(rep(month.abb[1:3], 3), levels=month.abb[1:3]),
  vals = c(10, 20, 30, 6, 14, 40, 30, 20, 10),
  col = rep(c("blue", "black", "red"), 3),
  fct = c(rep("Thing 1", 3),
          rep("Thing 2", 3),
          rep("Thing 3", 3))
) -> xdf

xdf %>%
  count(parts, wt = vals) %>%
  ggplot(aes(fill = parts, values = n)) +
  geom_waffle(n_rows = 20, size = 0.33, colour = "white", flip = TRUE) +
  scale_fill_manual(
    name = NULL,
    values = c("#a40000", "#c68958", "#ae6056"),
    labels = c("Fruit", "Sammich", "Pizza")
  ) +
  coord_equal() +
  theme_ipsum_rc(grid="") +
  theme_enhance_waffle()


xdf %>%
  count(parts, wt = vals) %>%
  ggplot(aes(label = parts, values = n)) +
  geom_pictogram(n_rows = 10, aes(colour = parts), flip = TRUE, make_proportional = TRUE) +
  scale_color_manual(
    name = NULL,
    values = c("#a40000", "#c68958", "#ae6056"),
    labels = c("Fruit", "Sammich", "Pizza")
  ) +
  scale_label_pictogram(
    name = NULL,
    values = c("apple-alt", "bread-slice", "pizza-slice"),
    labels = c("Fruit", "Sammich", "Pizza")
  ) +
  coord_equal() +
  theme_ipsum_rc(grid="") +
  theme_enhance_waffle() +
  theme(legend.key.height = unit(2.25, "line")) +
  theme(legend.text = element_text(size = 10, hjust = 0, vjust = 0.75))


xdf %>%
  count(parts, wt = vals) %>%
  ggplot(aes(label = parts, values = n)) +
  geom_pictogram(
    n_rows = 20, size = 6, aes(colour = parts), flip = TRUE,
    family = "FontAwesome5Brands-Regular"
  ) +
  scale_color_manual(
    name = NULL,
    values = c("#073f9c", "black", "#f34323"),
    labels = c("BitBucket", "GitHub", "Other")
  ) +
  scale_label_pictogram(
    name = NULL,
    values = c("bitbucket", "github", "git-alt"),
    labels = c("BitBucket", "GitHub", "Other")
  ) +
  coord_equal() +
  theme_ipsum_rc(grid="") +
  theme_enhance_waffle() +
  theme(legend.text = element_text(hjust = 0, vjust = 1))

Geoms!

library(hrbrthemes)
library(waffle)
library(tidyverse)

tibble(
  parts = factor(rep(month.abb[1:3], 3), levels=month.abb[1:3]),
  values = c(10, 20, 30, 6, 14, 40, 30, 20, 10),
  fct = c(rep("Thing 1", 3), rep("Thing 2", 3), rep("Thing 3", 3))
) -> xdf

ggplot(xdf, aes(fill=parts, values=values)) +
  geom_waffle(color = "white", size=1.125, n_rows = 6) +
  facet_wrap(~fct, ncol=1) +
  scale_x_discrete(expand=c(0,0)) +
  scale_y_discrete(expand=c(0,0)) +
  ggthemes::scale_fill_tableau(name=NULL) +
  coord_equal() +
  labs(
    title = "Faceted Waffle Geoms"
  ) +
  theme_ipsum_rc(grid="") +
  theme_enhance_waffle()

Waffle Bar Charts with scales!

library(dplyr)
library(waffle)

storms %>% 
  filter(year >= 2010) %>% 
  count(year, status) -> storms_df

ggplot(storms_df, aes(fill = status, values = n)) +
  geom_waffle(color = "white", size = .25, n_rows = 10, flip = TRUE) +
  facet_wrap(~year, nrow = 1, strip.position = "bottom") +
  scale_x_discrete() + 
  scale_y_continuous(labels = function(x) x * 10, # make this multiplyer the same as n_rows
                     expand = c(0,0)) +
  ggthemes::scale_fill_tableau(name=NULL) +
  coord_equal() +
  labs(
    title = "Faceted Waffle Bar Chart",
    subtitle = "{dplyr} storms data",
    x = "Year",
    y = "Count"
  ) +
  theme_minimal(base_family = "Roboto Condensed") +
  theme(panel.grid = element_blank(), axis.ticks.y = element_line()) +
  guides(fill = guide_legend(reverse = TRUE))

Basic example

parts <- c(80, 30, 20, 10)
waffle(parts, rows = 8)

Use a data frame

parts <- data.frame(
  names = LETTERS[1:4],
  vals = c(80, 30, 20, 10)
)

waffle(parts, rows = 8)

Slightly more complex example

parts <- c(`Un-breached\nUS Population` = (318 - 11 - 79), `Premera` = 11, `Anthem` = 79)
waffle(
  parts, rows = 8, size = 1, 
  colors = c("#969696", "#1879bf", "#009bda"), legend_pos = "bottom"
)

Health records breaches as fraction of US Population

One square == 1m ppl

waffle(
  parts / 10, rows = 3,
  colors = c("#969696", "#1879bf", "#009bda")
)

Health records breaches as fraction of US Population

(One square == 10m ppl)

library(extrafont)

waffle(
  parts / 10, rows = 3, colors = c("#969696", "#1879bf", "#009bda"),
  use_glyph = "medkit", size = 8
) + expand_limits(y = c(0, 4))

Replicating an old favourite

Via: https://www.nytimes.com/2008/07/20/business/20debt.html

savings <- c(
  `Mortgage\n($84,911)` = 84911, `Auto and\ntuition loans\n($14,414)` = 14414,
  `Home equity loans\n($10,062)` = 10062, `Credit Cards\n($8,565)` = 8565
)
waffle(
  savings / 392, rows = 7, size = 0.5, legend_pos = "bottom",
  colors = c("#c7d4b6", "#a3aabd", "#a0d0de", "#97b5cf")
)

Average Household Savings Each Year

(1 square == $392)

More replication

Similar to https://eagereyes.org/techniques/square-pie-charts

professional <- c(`Male` = 44, `Female (56%)` = 56)
waffle(
  professional, rows = 10, size = 0.5,
  colors = c("#af9139", "#544616")
)

Keeps factor by default levels now

With:

iron(
  waffle(c(thing1 = 0, thing2 = 100), rows = 5),
  waffle(c(thing1 = 25, thing2 = 75), rows = 5)
)

Without (you can disable this via keep parameter now):

iron(
  waffle(c(thing1 = 0, thing2 = 100), rows = 5, keep = FALSE),
  waffle(c(thing1 = 25, thing2 = 75), rows = 5, keep = FALSE)
)

Professional Workforce Makeup

Iron example (left-align & padding for multiple plots)

pain.adult.1997 <- c(`YOY (406)` = 406, `Adult (24)` = 24)

waffle(
  pain.adult.1997 / 2, rows = 7, size = 0.5,
  colors = c("#c7d4b6", "#a3aabd"),
  title = "Paine Run Brook Trout Abundance (1997)",
  xlab = "1 square = 2 fish", pad = 3
) -> A

pine.adult.1997 <- c(`YOY (221)` = 221, `Adult (143)` = 143)

waffle(
  pine.adult.1997 / 2, rows = 7, size = 0.5,
  colors = c("#c7d4b6", "#a3aabd"),
  title = "Piney River Brook Trout Abundance (1997)",
  xlab = "1 square = 2 fish", pad = 8
) -> B

stan.adult.1997 <- c(`YOY (270)` = 270, `Adult (197)` = 197)

waffle(
  stan.adult.1997 / 2, rows = 7, size = 0.5,
  colors = c("#c7d4b6", "#a3aabd"),
  title = "Staunton River Trout Abundance (1997)",
  xlab = "1 square = 2 fish"
) -> C

iron(A, B, C)

Package Code Metrics

cloc::cloc_pkg_md()
Lang# Files(%)LoC(%)Blank lines(%)# Lines(%)
R160.896280.622090.614300.7
Rmd20.113830.381350.391840.3

Code of Conduct

Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms.

Download Details:

Author: hrbrmstr
Source Code: https://github.com/hrbrmstr/waffle 

#r #datavisualization #charts 

Waffle: Make Waffle (square Pie) Charts in R
Nat  Grady

Nat Grady

1659821280

Opinionated, Typographic-centric Ggplot2 Themes & Theme Components

hrbrthemes

Additional Themes and Theme Components for ‘ggplot2’


This is a very focused package that provides typography-centric themes and theme components for ggplot2. It’s a an extract/riff of hrbrmisc created by request.

The core theme: theme_ipsum (“ipsum” is Latin for “precise”) uses Arial Narrow which should be installed on practically any modern system, so it’s “free”-ish. This font is condensed, has solid default kerning pairs and geometric numbers. That’s what I consider the “font trifecta” must-have for charts. An additional quality for fonts for charts is that they have a diversity of weights. Arial Narrow (the one on most systems, anyway) does not have said diversity but this quality is not (IMO) a “must have”.

The following functions are implemented/objects are exported:

Themes:

  • theme_ipsum: Arial Narrow
  • theme_ipsum_gs: Goldman Sans Condensed
  • theme_ipsum_es: Econ Sans Condensed
  • theme_ipsum_rc: Roboto Condensed
  • theme_ipsum_ps: IBM Plex Sans font
  • theme_ipsum_pub: Public Sans
  • theme_ipsum_tw: Titilium Web
  • theme_modern_rc: Roboto Condensed dark theme
  • theme_ft_rc: Dark theme based on FT’s dark theme (Roboto Condensed)

Scales (that align with various themes):

  • scale_color_ipsum: Discrete color & fill scales based on the ipsum palette
  • scale_colour_ipsum: Discrete color & fill scales based on the ipsum palette
  • scale_fill_ipsum: Discrete color & fill scales based on the ipsum palette
  • scale_color_ft: Discrete color & fill scales based on the FT palette
  • scale_colour_ft: Discrete color & fill scales based on the FT palette
  • scale_fill_ft: Discrete color & fill scales based on the FT palette
  • scale_x_comma: X & Y scales with opinionated presets for percent & comma label formats
  • scale_x_percent: X & Y scales with opinionated presets for percent & comma label formats
  • scale_y_comma: X & Y scales with opinionated presets for percent & comma label formats
  • scale_y_percent: X & Y scales with opinionated presets for percent & comma label formats

Palettes/Named Colors:

  • ipsum_pal: A muted, qualitative color palette
  • ft_cols: FT color palette
  • ft_pal: A bright qualitative color palette
  • ft_text_col: FT color palette

Fonts:

  • font_an: Arial Narrow font name R variable aliases
  • font_es: Econ Sans font name R variable aliases
  • font_es_bold: Econ Sans font name R variable aliases
  • font_es_light: Econ Sans font name R variable aliases
  • font_rc: Roboto Condensed font name R variable aliases
  • font_rc_light: Roboto Condensed font name R variable aliases
  • font_pub: Public Sans font name R variable aliases
  • font_pub_bold: Public Sans font name R variable aliases
  • font_pub_light: Public Sans font name R variable aliases
  • font_pub_thin: Public Sans font name R variable aliases
  • font_ps: PlexSans font name R variable aliases
  • font_ps_light: PlexSans font name R variable aliases
  • font_tw: Titillium Web font name R variable aliases
  • font_tw_bold: Titillium Web font name R variable aliases
  • font_tw_light: Titillium Web font name R variable aliases

R Markdown:

  • ipsum: ipsum R markdown template
  • ipsum_pdf: ipsum R markdown template for PDF output

Utilities:

  • flush_ticks: Makes axis text labels flush on the ends
  • ft_geom_defaults: Change geom defaults from black to custom lights for the FT theme
  • gg_check: Spell check ggplot2 plot labels
  • import_econ_sans: Import Econ Sans Condensed font for use in charts
  • import_plex_sans: Import IBM Plex Sans font for use in charts
  • import_roboto_condensed: Import Roboto Condensed font for use in charts
  • import_titillium_web: Import Titillium Web font for use in charts
  • modern_geom_defaults: Change geom defaults from black to white for the modern theme
  • update_geom_font_defaults: Update matching font defaults for text geoms

Installation

install.packages("hrbrthemes") # NOTE: CRAN version is 0.8.0
# or
install.packages("hrbrthemes", repos = c("https://cinc.rud.is", "https://cloud.r-project.org/"))
# or
remotes::install_git("https://git.rud.is/hrbrmstr/hrbrthemes.git")
# or
remotes::install_git("https://git.sr.ht/~hrbrmstr/hrbrthemes")
# or
remotes::install_gitlab("hrbrmstr/hrbrthemes")
# or
remotes::install_bitbucket("hrbrmstr/hrbrthemes")
# or
remotes::install_github("hrbrmstr/hrbrthemes")

NOTE: To use the ‘remotes’ install options you will need to have the {remotes} package installed.

Usage

library(hrbrthemes)
library(gcookbook)
library(tidyverse)

# current verison
packageVersion("hrbrthemes")
## [1] '0.8.6'

Base theme (Arial Narrow)

ggplot(mtcars, aes(mpg, wt)) +
  geom_point() +
  labs(x="Fuel efficiency (mpg)", y="Weight (tons)",
       title="Seminal ggplot2 scatterplot example",
       subtitle="A plot that is only useful for demonstration purposes",
       caption="Brought to you by the letter 'g'") + 
  theme_ipsum()

Roboto Condensed

ggplot(mtcars, aes(mpg, wt)) +
  geom_point() +
  labs(x="Fuel efficiency (mpg)", y="Weight (tons)",
       title="Seminal ggplot2 scatterplot example",
       subtitle="A plot that is only useful for demonstration purposes",
       caption="Brought to you by the letter 'g'") + 
  theme_ipsum_rc()

New FT Theme!

ggplot(mtcars, aes(mpg, wt)) +
  geom_point(color = ft_cols$yellow) +
  labs(x="Fuel efficiency (mpg)", y="Weight (tons)",
       title="Seminal ggplot2 scatterplot example",
       subtitle="A plot that is only useful for demonstration purposes",
       caption="Brought to you by the letter 'g'") + 
  theme_ft_rc()

IBM Plex Sans

ggplot(mpg, aes(displ, hwy)) +
  geom_jitter(aes(color=class, fill=class), size=3, shape=21, alpha=1/2) +
  scale_x_continuous(expand=c(0,0), limits=c(1, 8), breaks=1:8) +
  scale_y_continuous(expand=c(0,0), limits=c(10, 50)) +
  scale_color_ipsum() +
  scale_fill_ipsum() +
  facet_wrap(~class, scales="free") +
  labs(
    title="IBM Plex Sans Test",
    subtitle="This is a subtitle to see the how it looks in IBM Plex Sans",
    caption="Source: hrbrthemes & IBM"
  ) +
  theme_ipsum_ps(grid="XY", axis="xy") +
  theme(legend.position="none") -> gg

flush_ticks(gg)
## theme(axis.text.x=element_text(hjust=c(0, rep(0.5, 6), 1))) +
## theme(axis.text.y=element_text(vjust=c(0, rep(0.5, 3), 1)))

Titillium Web

ggplot(mpg, aes(displ, hwy)) +
  geom_jitter(aes(color=class, fill=class), size=3, shape=21, alpha=1/2) +
  scale_x_continuous(expand=c(0,0), limits=c(1, 8), breaks=1:8) +
  scale_y_continuous(expand=c(0,0), limits=c(10, 50)) +
  scale_color_ipsum() +
  scale_fill_ipsum() +
  facet_wrap(~class, scales="free") +
  labs(
    title="Titillium Web",
    subtitle="This is a subtitle to see the how it looks in Titillium Web",
    caption="Source: hrbrthemes & Google"
  ) +
  theme_ipsum_tw(grid="XY", axis="xy") +
  theme(legend.position="none") -> gg

flush_ticks(gg)
## theme(axis.text.x=element_text(hjust=c(0, rep(0.5, 6), 1))) +
## theme(axis.text.y=element_text(vjust=c(0, rep(0.5, 3), 1)))

Scales (Color/Fill)

ggplot(mtcars, aes(mpg, wt)) +
  geom_point(aes(color=factor(carb))) +
  labs(x="Fuel efficiency (mpg)", y="Weight (tons)",
       title="Seminal ggplot2 scatterplot example",
       subtitle="A plot that is only useful for demonstration purposes",
       caption="Brought to you by the letter 'g'") + 
  scale_color_ipsum() +
  theme_ipsum_rc()

Scales (Axis)

count(mpg, class) %>% 
  mutate(pct=n/sum(n)) %>% 
  ggplot(aes(class, pct)) +
  geom_col() +
  scale_y_percent() +
  labs(x="Fuel efficiency (mpg)", y="Weight (tons)",
       title="Seminal ggplot2 column chart example with percents",
       subtitle="A plot that is only useful for demonstration purposes",
       caption="Brought to you by the letter 'g'") + 
  theme_ipsum(grid="Y")

ggplot(uspopage, aes(x=Year, y=Thousands, fill=AgeGroup)) + 
  geom_area() +
  scale_fill_ipsum() +
  scale_x_continuous(expand=c(0,0)) +
  scale_y_comma() +
  labs(title="Age distribution of population in the U.S., 1900-2002",
       subtitle="Example data from the R Graphics Cookbook",
       caption="Source: R Graphics Cookbook") +
  theme_ipsum_rc(grid="XY") +
  theme(axis.text.x=element_text(hjust=c(0, 0.5, 0.5, 0.5, 1))) +
  theme(legend.position="bottom")

update_geom_font_defaults(font_rc_light)

count(mpg, class) %>% 
  mutate(n=n*2000) %>% 
  arrange(n) %>% 
  mutate(class=factor(class, levels=class)) %>% 
  ggplot(aes(class, n)) +
  geom_col() +
  geom_text(aes(label=scales::comma(n)), hjust=0, nudge_y=2000) +
  scale_y_comma(limits=c(0,150000)) +
  coord_flip() +
  labs(x="Fuel efficiency (mpg)", y="Weight (tons)",
       title="Seminal ggplot2 column chart example with commas",
       subtitle="A plot that is only useful for demonstration purposes, esp since you'd never\nreally want direct labels and axis labels",
       caption="Brought to you by the letter 'g'") + 
  theme_ipsum_rc(grid="X")

Spellcheck ggplot2 labels

df <- data.frame(x=c(20, 25, 30), y=c(4, 4, 4), txt=c("One", "Two", "Three"))

ggplot(mtcars, aes(mpg, wt)) +
  geom_point() +
  labs(x="This is some txt", y="This is more text",
       title="Thisy is a titlle",
       subtitle="This is a subtitley",
       caption="This is a captien") +
  theme_ipsum_rc(grid="XY") -> gg

gg_check(gg)
## Possible misspelled words in [title]: (Thisy, titlle)
## Possible misspelled words in [subtitle]: (subtitley)
## Possible misspelled words in [caption]: (captien)

hrbrthemes Metrics

Lang# Files(%)LoC(%)Blank lines(%)# Lines(%)
R240.8917240.803270.729080.84
HTML10.042970.14320.0720.00
Rmd20.071290.06980.211680.16

Code of Conduct

Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms.

Author: Hrbrmstr
Source Code: https://github.com/hrbrmstr/hrbrthemes 
License: View license

#r #visualization #datavisualization 

Opinionated, Typographic-centric Ggplot2 Themes & Theme Components
Nat  Grady

Nat Grady

1659813780

GGanimate: A Grammar Of animated Graphics

gganimate 

gganimate extends the grammar of graphics as implemented by ggplot2 to include the description of animation. It does this by providing a range of new grammar classes that can be added to the plot object in order to customise how it should change with time.

  • transition_*() defines how the data should be spread out and how it relates to itself across time.
  • view_*() defines how the positional scales should change along the animation.
  • shadow_*() defines how data from other points in time should be presented in the given point in time.
  • enter_*()/exit_*() defines how new data should appear and how old data should disappear during the course of the animation.
  • ease_aes() defines how different aesthetics should be eased during transitions.

An Example

All of the above might seem a bit abstract. Let’s try with a contrived example:

library(ggplot2)
library(gganimate)

ggplot(mtcars, aes(factor(cyl), mpg)) + 
  geom_boxplot() + 
  # Here comes the gganimate code
  transition_states(
    gear,
    transition_length = 2,
    state_length = 1
  ) +
  enter_fade() + 
  exit_shrink() +
  ease_aes('sine-in-out')

Here we take a simple boxplot of fuel consumption as a function of cylinders and lets it transition between the number of gears available in the cars. As this is a discrete split (gear being best described as an ordered factor) we use transition_states and provides a relative length to use for transition and state view. As not all combinations of data is present there are states missing a box. We define that when a box appears it should fade into view, whereas at should shrink away when it disappear. Lastly we decide to use a sinusoidal easing for all our aesthetics (here, only y is changing)

Installation

gganimate is available on CRAN and can be installed with install.packages('gganimate'). If you wish to install the development version you can install directly from github using devtools:

# install.packages('devtools')
devtools::install_github('thomasp85/gganimate')

Yet Another Example

It is impossible to cover everything possible with gganimate in a README, but animations are fun, so let’s at least have one more:

library(gapminder)

ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, colour = country)) +
  geom_point(alpha = 0.7, show.legend = FALSE) +
  scale_colour_manual(values = country_colors) +
  scale_size(range = c(2, 12)) +
  scale_x_log10() +
  facet_wrap(~continent) +
  # Here comes the gganimate specific bits
  labs(title = 'Year: {frame_time}', x = 'GDP per capita', y = 'life expectancy') +
  transition_time(year) +
  ease_aes('linear')

In this example we see the use of transition_time() which can be used with continuous variables such as year. With this transition it is not necessary to provide transition and state length as the “transition variable” provides this directly (e.g. it should take twice as long to transition between 1980 and 1990 compared to 2000 to 2005). We also see the use of string literal interpolation in titles. gganimate lets you specify variables to evaluate inside titles and different transitions provide different type of information to use.

Where is my animation?

gganimate mimics the way ggplot2 renders its output, in that the rendering is done automatically when the gganim object is printed. Under the hood, the animate() function is called which renders the frame and passes the frames to a renderer functions which takes care of combining them to the final animation. The default renderer is gifski_renderer() which returns a gif_image object which is a simple wrapper around a path to a gif file. If animate() has been called implicitly as part of print the gif_image object is available using the last_animation() function (analogous to ggplot2::last_plot()). In order to save the animation to a specific location, you can use the anim_save() function which, like ggplot2::ggsave, defaults to taking the last rendered animation and writes it to a file.

I don’t like gifs…

gif is a fantastic format for animations due to its wide support, but sometimes another format is required. gganimate is agnostic to the renderer and while the default is to use gifski to combine the frames into a gif, it doesn’t have to be so. By passing an alternate renderer to the animate() function you can control the animation format, and gganimate comes with a bunch (and you can write your own). To create video files you can e.g. use the ffmpeg_renderer():

p <- ggplot(airquality, aes(Day, Temp)) + 
  geom_line(size = 2, colour = 'steelblue') + 
  transition_states(Month, 4, 1) + 
  shadow_mark(size = 1, colour = 'grey')
animate(p, renderer = ffmpeg_renderer())

Video output are automatically embedded in RMarkdown documents, but GitHub strips video when rendering READMEs so you can’t see it here

Further there’s support for rendering to sprite sheets if that is your vice.

Old API

This is the second iteration of the gganimate package. The first, developed by David Robinson had a very different API, and relied on specifying animation frame membership inside aes() blocks in the geom_*() calls. This approach was easy to grasp, but essentially limited in capabilities and has thus been abandoned for a more thorough grammar.

Code written for the old API will not work with this gganimate version and there will not come a future support for it. If you wish to continue using the old API then avoid upgrading gganimate. If you’ve already upgraded and wish to downgrade, the latest version of the old API is available as a GitHub release.

If you wish to convert your old animations to the new API, the closest you get is probably with transition_manual, even though it is not completely substitutable:

# Old code
ggplot(mtcars) + 
  geom_boxplot(aes(factor(cyl), mpg, frame = gear))

# New code
ggplot(mtcars) + 
  geom_boxplot(aes(factor(cyl), mpg)) + 
  transition_manual(gear)

Author: Thomasp85
Source Code: https://github.com/thomasp85/gganimate 
License: View license

#r #animation #datavisualization 

GGanimate: A Grammar Of animated Graphics