1678114672
A wrapper around InheritedWidget to make them easier to use and more reusable.
By using provider
instead of manually writing InheritedWidget, you get:
To read more about a provider
, see its documentation.
See also:
provider
+ ChangeNotifierprovider
+ ChangeNotifierprovider
in their architectureinitialData
for both FutureProvider
and StreamProvider
is now required.
To migrate, what used to be:
FutureProvider<int>(
create: (context) => Future.value(42),
child: MyApp(),
)
Widget build(BuildContext context) {
final value = context.watch<int>();
return Text('$value');
}
is now:
FutureProvider<int?>(
initialValue: null,
create: (context) => Future.value(42),
child: MyApp(),
)
Widget build(BuildContext context) {
// be sure to specify the ? in watch<int?>
final value = context.watch<int?>();
return Text('$value');
}
ValueListenableProvider
is removed
To migrate, you can instead use Provider
combined with ValueListenableBuilder
:
ValueListenableBuilder<int>(
valueListenable: myValueListenable,
builder: (context, value, _) {
return Provider<int>.value(
value: value,
child: MyApp(),
);
}
)
Providers allow you to not only expose a value, but also create, listen, and dispose of it.
To expose a newly created object, use the default constructor of a provider. Do not use the .value
constructor if you want to create an object, or you may otherwise have undesired side effects.
See this StackOverflow answer which explains why using the .value
constructor to create values is undesired.
create
.Provider(
create: (_) => MyModel(),
child: ...
)
Provider.value
to create your object.ChangeNotifierProvider.value(
value: MyModel(),
child: ...
)
DON'T create your object from variables that can change over time.
In such a situation, your object would never update when the value changes.
int count;
Provider(
create: (_) => MyModel(count),
child: ...
)
If you want to pass variables that can change over time to your object, consider using ProxyProvider
:
int count;
ProxyProvider0(
update: (_, __) => MyModel(count),
child: ...
)
NOTE:
When using the create
/update
callback of a provider, it is worth noting that this callback is called lazily by default.
This means that until the value is requested at least once, the create
/update
callbacks won't be called.
This behavior can be disabled if you want to pre-compute some logic, using the lazy
parameter:
MyProvider(
create: (_) => Something(),
lazy: false,
)
If you already have an object instance and want to expose it, it would be best to use the .value
constructor of a provider.
Failing to do so may call your object dispose
method when it is still in use.
ChangeNotifierProvider.value
to provide an existing ChangeNotifier.MyChangeNotifier variable;
ChangeNotifierProvider.value(
value: variable,
child: ...
)
MyChangeNotifier variable;
ChangeNotifierProvider(
create: (_) => variable,
child: ...
)
The easiest way to read a value is by using the extension methods on [BuildContext]:
context.watch<T>()
, which makes the widget listen to changes on T
context.read<T>()
, which returns T
without listening to itcontext.select<T, R>(R cb(T value))
, which allows a widget to listen to only a small part of T
.One can also use the static method Provider.of<T>(context)
, which will behave similarly to watch
. When the listen
parameter is set to false
(as in Provider.of<T>(context, listen: false)
), then it will behave similarly to read
.
It's worth noting that context.read<T>()
won't make a widget rebuild when the value changes and it cannot be called inside StatelessWidget.build
/State.build
. On the other hand, it can be freely called outside of these methods.
These methods will look up in the widget tree starting from the widget associated with the BuildContext
passed and will return the nearest variable of type T
found (or throw if nothing is found).
This operation is O(1). It doesn't involve walking in the widget tree.
Combined with the first example of exposing a value, this widget will read the exposed String
and render "Hello World."
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Text(
// Don't forget to pass the type of the object you want to obtain to `watch`!
context.watch<String>(),
);
}
}
Alternatively, instead of using these methods, we can use Consumer and Selector.
These can be useful for performance optimizations or when it is difficult to obtain a BuildContext
descendant of the provider.
See the FAQ or the documentation of Consumer and Selector for more information.
Sometimes, we may want to support cases where a provider does not exist. An example would be for reusable widgets that could be used in various locations, including outside of a provider.
To do so, when calling context.watch
/context.read
, make the generic type nullable. Such that instead of:
context.watch<Model>()
which will throw a ProviderNotFoundException
if no matching providers are found, do:
context.watch<Model?>()
which will try to obtain a matching provider. But if none are found, null
will be returned instead of throwing.
When injecting many values in big applications, Provider
can rapidly become pretty nested:
Provider<Something>(
create: (_) => Something(),
child: Provider<SomethingElse>(
create: (_) => SomethingElse(),
child: Provider<AnotherThing>(
create: (_) => AnotherThing(),
child: someWidget,
),
),
),
To:
MultiProvider(
providers: [
Provider<Something>(create: (_) => Something()),
Provider<SomethingElse>(create: (_) => SomethingElse()),
Provider<AnotherThing>(create: (_) => AnotherThing()),
],
child: someWidget,
)
The behavior of both examples is strictly the same. MultiProvider
only changes the appearance of the code.
Since the 3.0.0, there is a new kind of provider: ProxyProvider
.
ProxyProvider
is a provider that combines multiple values from other providers into a new object and sends the result to Provider
.
That new object will then be updated whenever one of the provider we depend on gets updated.
The following example uses ProxyProvider
to build translations based on a counter coming from another provider.
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => Counter()),
ProxyProvider<Counter, Translations>(
update: (_, counter, __) => Translations(counter.value),
),
],
child: Foo(),
);
}
class Translations {
const Translations(this._value);
final int _value;
String get title => 'You clicked $_value times';
}
It comes under multiple variations, such as:
ProxyProvider
vs ProxyProvider2
vs ProxyProvider3
, ...
That digit after the class name is the number of other providers that ProxyProvider
depends on.
ProxyProvider
vs ChangeNotifierProxyProvider
vs ListenableProxyProvider
, ...
They all work similarly, but instead of sending the result into a Provider
, a ChangeNotifierProxyProvider
will send its value to a ChangeNotifierProvider
.
Flutter comes with a devtool that shows what the widget tree is at a given moment.
Since providers are widgets, they are also visible in that devtool:
From there, if you click on one provider, you will be able to see the value it exposes:
(screenshot of the devtools using the example
folder)
By default, the devtool relies on toString
, which defaults to "Instance of MyClass".
To have something more useful, you have two solutions:
use the Diagnosticable API from Flutter.
For most cases, I will use DiagnosticableTreeMixin on your objects, followed by a custom implementation of debugFillProperties.
class MyClass with DiagnosticableTreeMixin {
MyClass({this.a, this.b});
final int a;
final String b;
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
// list all the properties of your class here.
// See the documentation of debugFillProperties for more information.
properties.add(IntProperty('a', a));
properties.add(StringProperty('b', b));
}
}
Override toString
.
If you cannot use DiagnosticableTreeMixin (like if your class is in a package that does not depend on Flutter), then you can override toString
.
This is easier than using DiagnosticableTreeMixin but is less powerful: You will not be able to expand/collapse the details of your object.
class MyClass with DiagnosticableTreeMixin {
MyClass({this.a, this.b});
final int a;
final String b;
@override
String toString() {
return '$runtimeType(a: $a, b: $b)';
}
}
initState
. What can I do?This exception happens because you're trying to listen to a provider from a life-cycle that will never ever be called again.
It means that you either should use another life-cycle (build
), or explicitly specify that you do not care about updates.
As such, instead of:
initState() {
super.initState();
print(context.watch<Foo>().value);
}
you can do:
Value value;
Widget build(BuildContext context) {
final value = context.watch<Foo>().value;
if (value != this.value) {
this.value = value;
print(value);
}
}
which will print value
whenever it changes (and only when it changes).
Alternatively, you can do:
initState() {
super.initState();
print(context.read<Foo>().value);
}
Which will print value
once and ignore updates.
You can make your provided object implement ReassembleHandler
:
class Example extends ChangeNotifier implements ReassembleHandler {
@override
void reassemble() {
print('Did hot-reload');
}
}
Then used typically with provider
:
ChangeNotifierProvider(create: (_) => Example()),
This likely happens because you are modifying the ChangeNotifier from one of its descendants while the widget tree is building.
A typical situation where this happens is when starting an http request, where the future is stored inside the notifier:
initState() {
super.initState();
context.read<MyNotifier>().fetchSomething();
}
This is not allowed because the state update is synchronous.
This means that some widgets may build before the mutation happens (getting an old value), while other widgets will build after the mutation is complete (getting a new value). This could cause inconsistencies in your UI and is therefore not allowed.
Instead, you should perform that mutation in a place that would affect the entire tree equally:
directly inside the create
of your provider/constructor of your model:
class MyNotifier with ChangeNotifier {
MyNotifier() {
_fetchSomething();
}
Future<void> _fetchSomething() async {}
}
This is useful when there's no "external parameter".
asynchronously at the end of the frame:
initState() {
super.initState();
Future.microtask(() =>
context.read<MyNotifier>().fetchSomething(someValue);
);
}
It is slightly less ideal, but allows passing parameters to the mutation.
No.
You can use any object to represent your state. For example, an alternate architecture is to use Provider.value()
combined with a StatefulWidget
.
Here's a counter example using such architecture:
class Example extends StatefulWidget {
const Example({Key key, this.child}) : super(key: key);
final Widget child;
@override
ExampleState createState() => ExampleState();
}
class ExampleState extends State<Example> {
int _count;
void increment() {
setState(() {
_count++;
});
}
@override
Widget build(BuildContext context) {
return Provider.value(
value: _count,
child: Provider.value(
value: this,
child: widget.child,
),
);
}
}
where we can read the state by doing:
return Text(context.watch<int>().toString());
and modify the state with:
return FloatingActionButton(
onPressed: () => context.read<ExampleState>().increment(),
child: Icon(Icons.plus_one),
);
Alternatively, you can create your own provider.
Yes. provider
exposes all the small components that make a fully-fledged provider.
This includes:
SingleChildStatelessWidget
, to make any widget works with MultiProvider
. This interface is exposed as part of package:provider/single_child_widget
InheritedProvider, the generic InheritedWidget
obtained when doing context.watch
.
Here's an example of a custom provider to use ValueNotifier
as the state: https://gist.github.com/rrousselGit/4910f3125e41600df3c2577e26967c91
Instead of context.watch
, you can use context.select
to listen only to the specific set of properties on the obtained object.
For example, while you can write:
Widget build(BuildContext context) {
final person = context.watch<Person>();
return Text(person.name);
}
It may cause the widget to rebuild if something other than name
changes.
Instead, you can use context.select
to listen only to the name
property:
Widget build(BuildContext context) {
final name = context.select((Person p) => p.name);
return Text(name);
}
This way, the widget won't unnecessarily rebuild if something other than name
changes.
Similarly, you can use Consumer/Selector. Their optional child
argument allows rebuilding only a particular part of the widget tree:
Foo(
child: Consumer<A>(
builder: (_, a, child) {
return Bar(a: a, child: child);
},
child: Baz(),
),
)
In this example, only Bar
will rebuild when A
updates. Foo
and Baz
won't unnecessarily rebuild.
No. While you can have multiple providers sharing the same type, a widget will be able to obtain only one of them: the closest ancestor.
Instead, it would help if you explicitly gave both providers a different type.
Instead of:
Provider<String>(
create: (_) => 'England',
child: Provider<String>(
create: (_) => 'London',
child: ...,
),
),
Prefer:
Provider<Country>(
create: (_) => Country('England'),
child: Provider<City>(
create: (_) => City('London'),
child: ...,
),
),
Yes, a type hint must be given to the compiler to indicate the interface will be consumed, with the implementation provided in create.
abstract class ProviderInterface with ChangeNotifier {
...
}
class ProviderImplementation with ChangeNotifier implements ProviderInterface {
...
}
class Foo extends StatelessWidget {
@override
build(context) {
final provider = Provider.of<ProviderInterface>(context);
return ...
}
}
ChangeNotifierProvider<ProviderInterface>(
create: (_) => ProviderImplementation(),
child: Foo(),
),
provider
exposes a few different kinds of "provider" for different types of objects.
The complete list of all the objects available is here
name | description |
---|---|
Provider | The most basic form of provider. It takes a value and exposes it, whatever the value is. |
ListenableProvider | A specific provider for Listenable object. ListenableProvider will listen to the object and ask widgets which depend on it to rebuild whenever the listener is called. |
ChangeNotifierProvider | A specification of ListenableProvider for ChangeNotifier. It will automatically call ChangeNotifier.dispose when needed. |
ValueListenableProvider | Listen to a ValueListenable and only expose ValueListenable.value . |
StreamProvider | Listen to a Stream and expose the latest value emitted. |
FutureProvider | Takes a Future and updates dependents when the future completes. |
If you have a very large number of providers (150+), it is possible that some devices will throw a StackOverflowError
because you end-up building too many widgets at once.
In this situation, you have a few solutions:
If your application has a splash-screen, try mounting your providers over time instead of all at once.
You could do:
MultiProvider(
providers: [
if (step1) ...[
<lots of providers>,
],
if (step2) ...[
<some more providers>
]
],
)
where during your splash screen animation, you would do:
bool step1 = false;
bool step2 = false;
@override
initState() {
super.initState();
Future(() {
setState(() => step1 = true);
Future(() {
setState(() => step2 = true);
});
});
}
Consider opting out of using MultiProvider
. MultiProvider
works by adding a widget between every providers. Not using MultiProvider
can increase the limit before a StackOverflowError
is reached
Run this command:
With Flutter:
$ flutter pub add provider
This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get
):
dependencies:
provider: ^6.0.5
Alternatively, your editor might support flutter pub get
. Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:provider/provider.dart';
// ignore_for_file: public_member_api_docs, lines_longer_than_80_chars
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
/// This is a reimplementation of the default Flutter application using provider + [ChangeNotifier].
void main() {
runApp(
/// Providers are above [MyApp] instead of inside it, so that tests
/// can use [MyApp] while mocking the providers
MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => Counter()),
],
child: const MyApp(),
),
);
}
/// Mix-in [DiagnosticableTreeMixin] to have access to [debugFillProperties] for the devtool
// ignore: prefer_mixin
class Counter with ChangeNotifier, DiagnosticableTreeMixin {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
/// Makes `Counter` readable inside the devtools by listing all of its properties
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(IntProperty('count', count));
}
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Example'),
),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: const <Widget>[
Text('You have pushed the button this many times:'),
/// Extracted as a separate widget for performance optimization.
/// As a separate widget, it will rebuild independently from [MyHomePage].
///
/// This is totally optional (and rarely needed).
/// Similarly, we could also use [Consumer] or [Selector].
Count(),
],
),
),
floatingActionButton: FloatingActionButton(
key: const Key('increment_floatingActionButton'),
/// Calls `context.read` instead of `context.watch` so that it does not rebuild
/// when [Counter] changes.
onPressed: () => context.read<Counter>().increment(),
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
class Count extends StatelessWidget {
const Count({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Text(
/// Calls `context.watch` to make [Count] rebuild when [Counter] changes.
'${context.watch<Counter>().count}',
key: const Key('counterState'),
style: Theme.of(context).textTheme.headlineMedium,
);
}
}
Download Details:
Author: rrousselGit
Source Code: https://github.com/rrousselGit/provider
1667425440
Perl script converts PDF files to Gerber format
Pdf2Gerb generates Gerber 274X photoplotting and Excellon drill files from PDFs of a PCB. Up to three PDFs are used: the top copper layer, the bottom copper layer (for 2-sided PCBs), and an optional silk screen layer. The PDFs can be created directly from any PDF drawing software, or a PDF print driver can be used to capture the Print output if the drawing software does not directly support output to PDF.
The general workflow is as follows:
Please note that Pdf2Gerb does NOT perform DRC (Design Rule Checks), as these will vary according to individual PCB manufacturer conventions and capabilities. Also note that Pdf2Gerb is not perfect, so the output files must always be checked before submitting them. As of version 1.6, Pdf2Gerb supports most PCB elements, such as round and square pads, round holes, traces, SMD pads, ground planes, no-fill areas, and panelization. However, because it interprets the graphical output of a Print function, there are limitations in what it can recognize (or there may be bugs).
See docs/Pdf2Gerb.pdf for install/setup, config, usage, and other info.
#Pdf2Gerb config settings:
#Put this file in same folder/directory as pdf2gerb.pl itself (global settings),
#or copy to another folder/directory with PDFs if you want PCB-specific settings.
#There is only one user of this file, so we don't need a custom package or namespace.
#NOTE: all constants defined in here will be added to main namespace.
#package pdf2gerb_cfg;
use strict; #trap undef vars (easier debug)
use warnings; #other useful info (easier debug)
##############################################################################################
#configurable settings:
#change values here instead of in main pfg2gerb.pl file
use constant WANT_COLORS => ($^O !~ m/Win/); #ANSI colors no worky on Windows? this must be set < first DebugPrint() call
#just a little warning; set realistic expectations:
#DebugPrint("${\(CYAN)}Pdf2Gerb.pl ${\(VERSION)}, $^O O/S\n${\(YELLOW)}${\(BOLD)}${\(ITALIC)}This is EXPERIMENTAL software. \nGerber files MAY CONTAIN ERRORS. Please CHECK them before fabrication!${\(RESET)}", 0); #if WANT_DEBUG
use constant METRIC => FALSE; #set to TRUE for metric units (only affect final numbers in output files, not internal arithmetic)
use constant APERTURE_LIMIT => 0; #34; #max #apertures to use; generate warnings if too many apertures are used (0 to not check)
use constant DRILL_FMT => '2.4'; #'2.3'; #'2.4' is the default for PCB fab; change to '2.3' for CNC
use constant WANT_DEBUG => 0; #10; #level of debug wanted; higher == more, lower == less, 0 == none
use constant GERBER_DEBUG => 0; #level of debug to include in Gerber file; DON'T USE FOR FABRICATION
use constant WANT_STREAMS => FALSE; #TRUE; #save decompressed streams to files (for debug)
use constant WANT_ALLINPUT => FALSE; #TRUE; #save entire input stream (for debug ONLY)
#DebugPrint(sprintf("${\(CYAN)}DEBUG: stdout %d, gerber %d, want streams? %d, all input? %d, O/S: $^O, Perl: $]${\(RESET)}\n", WANT_DEBUG, GERBER_DEBUG, WANT_STREAMS, WANT_ALLINPUT), 1);
#DebugPrint(sprintf("max int = %d, min int = %d\n", MAXINT, MININT), 1);
#define standard trace and pad sizes to reduce scaling or PDF rendering errors:
#This avoids weird aperture settings and replaces them with more standardized values.
#(I'm not sure how photoplotters handle strange sizes).
#Fewer choices here gives more accurate mapping in the final Gerber files.
#units are in inches
use constant TOOL_SIZES => #add more as desired
(
#round or square pads (> 0) and drills (< 0):
.010, -.001, #tiny pads for SMD; dummy drill size (too small for practical use, but needed so StandardTool will use this entry)
.031, -.014, #used for vias
.041, -.020, #smallest non-filled plated hole
.051, -.025,
.056, -.029, #useful for IC pins
.070, -.033,
.075, -.040, #heavier leads
# .090, -.043, #NOTE: 600 dpi is not high enough resolution to reliably distinguish between .043" and .046", so choose 1 of the 2 here
.100, -.046,
.115, -.052,
.130, -.061,
.140, -.067,
.150, -.079,
.175, -.088,
.190, -.093,
.200, -.100,
.220, -.110,
.160, -.125, #useful for mounting holes
#some additional pad sizes without holes (repeat a previous hole size if you just want the pad size):
.090, -.040, #want a .090 pad option, but use dummy hole size
.065, -.040, #.065 x .065 rect pad
.035, -.040, #.035 x .065 rect pad
#traces:
.001, #too thin for real traces; use only for board outlines
.006, #minimum real trace width; mainly used for text
.008, #mainly used for mid-sized text, not traces
.010, #minimum recommended trace width for low-current signals
.012,
.015, #moderate low-voltage current
.020, #heavier trace for power, ground (even if a lighter one is adequate)
.025,
.030, #heavy-current traces; be careful with these ones!
.040,
.050,
.060,
.080,
.100,
.120,
);
#Areas larger than the values below will be filled with parallel lines:
#This cuts down on the number of aperture sizes used.
#Set to 0 to always use an aperture or drill, regardless of size.
use constant { MAX_APERTURE => max((TOOL_SIZES)) + .004, MAX_DRILL => -min((TOOL_SIZES)) + .004 }; #max aperture and drill sizes (plus a little tolerance)
#DebugPrint(sprintf("using %d standard tool sizes: %s, max aper %.3f, max drill %.3f\n", scalar((TOOL_SIZES)), join(", ", (TOOL_SIZES)), MAX_APERTURE, MAX_DRILL), 1);
#NOTE: Compare the PDF to the original CAD file to check the accuracy of the PDF rendering and parsing!
#for example, the CAD software I used generated the following circles for holes:
#CAD hole size: parsed PDF diameter: error:
# .014 .016 +.002
# .020 .02267 +.00267
# .025 .026 +.001
# .029 .03167 +.00267
# .033 .036 +.003
# .040 .04267 +.00267
#This was usually ~ .002" - .003" too big compared to the hole as displayed in the CAD software.
#To compensate for PDF rendering errors (either during CAD Print function or PDF parsing logic), adjust the values below as needed.
#units are pixels; for example, a value of 2.4 at 600 dpi = .0004 inch, 2 at 600 dpi = .0033"
use constant
{
HOLE_ADJUST => -0.004 * 600, #-2.6, #holes seemed to be slightly oversized (by .002" - .004"), so shrink them a little
RNDPAD_ADJUST => -0.003 * 600, #-2, #-2.4, #round pads seemed to be slightly oversized, so shrink them a little
SQRPAD_ADJUST => +0.001 * 600, #+.5, #square pads are sometimes too small by .00067, so bump them up a little
RECTPAD_ADJUST => 0, #(pixels) rectangular pads seem to be okay? (not tested much)
TRACE_ADJUST => 0, #(pixels) traces seemed to be okay?
REDUCE_TOLERANCE => .001, #(inches) allow this much variation when reducing circles and rects
};
#Also, my CAD's Print function or the PDF print driver I used was a little off for circles, so define some additional adjustment values here:
#Values are added to X/Y coordinates; units are pixels; for example, a value of 1 at 600 dpi would be ~= .002 inch
use constant
{
CIRCLE_ADJUST_MINX => 0,
CIRCLE_ADJUST_MINY => -0.001 * 600, #-1, #circles were a little too high, so nudge them a little lower
CIRCLE_ADJUST_MAXX => +0.001 * 600, #+1, #circles were a little too far to the left, so nudge them a little to the right
CIRCLE_ADJUST_MAXY => 0,
SUBST_CIRCLE_CLIPRECT => FALSE, #generate circle and substitute for clip rects (to compensate for the way some CAD software draws circles)
WANT_CLIPRECT => TRUE, #FALSE, #AI doesn't need clip rect at all? should be on normally?
RECT_COMPLETION => FALSE, #TRUE, #fill in 4th side of rect when 3 sides found
};
#allow .012 clearance around pads for solder mask:
#This value effectively adjusts pad sizes in the TOOL_SIZES list above (only for solder mask layers).
use constant SOLDER_MARGIN => +.012; #units are inches
#line join/cap styles:
use constant
{
CAP_NONE => 0, #butt (none); line is exact length
CAP_ROUND => 1, #round cap/join; line overhangs by a semi-circle at either end
CAP_SQUARE => 2, #square cap/join; line overhangs by a half square on either end
CAP_OVERRIDE => FALSE, #cap style overrides drawing logic
};
#number of elements in each shape type:
use constant
{
RECT_SHAPELEN => 6, #x0, y0, x1, y1, count, "rect" (start, end corners)
LINE_SHAPELEN => 6, #x0, y0, x1, y1, count, "line" (line seg)
CURVE_SHAPELEN => 10, #xstart, ystart, x0, y0, x1, y1, xend, yend, count, "curve" (bezier 2 points)
CIRCLE_SHAPELEN => 5, #x, y, 5, count, "circle" (center + radius)
};
#const my %SHAPELEN =
#Readonly my %SHAPELEN =>
our %SHAPELEN =
(
rect => RECT_SHAPELEN,
line => LINE_SHAPELEN,
curve => CURVE_SHAPELEN,
circle => CIRCLE_SHAPELEN,
);
#panelization:
#This will repeat the entire body the number of times indicated along the X or Y axes (files grow accordingly).
#Display elements that overhang PCB boundary can be squashed or left as-is (typically text or other silk screen markings).
#Set "overhangs" TRUE to allow overhangs, FALSE to truncate them.
#xpad and ypad allow margins to be added around outer edge of panelized PCB.
use constant PANELIZE => {'x' => 1, 'y' => 1, 'xpad' => 0, 'ypad' => 0, 'overhangs' => TRUE}; #number of times to repeat in X and Y directions
# Set this to 1 if you need TurboCAD support.
#$turboCAD = FALSE; #is this still needed as an option?
#CIRCAD pad generation uses an appropriate aperture, then moves it (stroke) "a little" - we use this to find pads and distinguish them from PCB holes.
use constant PAD_STROKE => 0.3; #0.0005 * 600; #units are pixels
#convert very short traces to pads or holes:
use constant TRACE_MINLEN => .001; #units are inches
#use constant ALWAYS_XY => TRUE; #FALSE; #force XY even if X or Y doesn't change; NOTE: needs to be TRUE for all pads to show in FlatCAM and ViewPlot
use constant REMOVE_POLARITY => FALSE; #TRUE; #set to remove subtractive (negative) polarity; NOTE: must be FALSE for ground planes
#PDF uses "points", each point = 1/72 inch
#combined with a PDF scale factor of .12, this gives 600 dpi resolution (1/72 * .12 = 600 dpi)
use constant INCHES_PER_POINT => 1/72; #0.0138888889; #multiply point-size by this to get inches
# The precision used when computing a bezier curve. Higher numbers are more precise but slower (and generate larger files).
#$bezierPrecision = 100;
use constant BEZIER_PRECISION => 36; #100; #use const; reduced for faster rendering (mainly used for silk screen and thermal pads)
# Ground planes and silk screen or larger copper rectangles or circles are filled line-by-line using this resolution.
use constant FILL_WIDTH => .01; #fill at most 0.01 inch at a time
# The max number of characters to read into memory
use constant MAX_BYTES => 10 * M; #bumped up to 10 MB, use const
use constant DUP_DRILL1 => TRUE; #FALSE; #kludge: ViewPlot doesn't load drill files that are too small so duplicate first tool
my $runtime = time(); #Time::HiRes::gettimeofday(); #measure my execution time
print STDERR "Loaded config settings from '${\(__FILE__)}'.\n";
1; #last value must be truthful to indicate successful load
#############################################################################################
#junk/experiment:
#use Package::Constants;
#use Exporter qw(import); #https://perldoc.perl.org/Exporter.html
#my $caller = "pdf2gerb::";
#sub cfg
#{
# my $proto = shift;
# my $class = ref($proto) || $proto;
# my $settings =
# {
# $WANT_DEBUG => 990, #10; #level of debug wanted; higher == more, lower == less, 0 == none
# };
# bless($settings, $class);
# return $settings;
#}
#use constant HELLO => "hi there2"; #"main::HELLO" => "hi there";
#use constant GOODBYE => 14; #"main::GOODBYE" => 12;
#print STDERR "read cfg file\n";
#our @EXPORT_OK = Package::Constants->list(__PACKAGE__); #https://www.perlmonks.org/?node_id=1072691; NOTE: "_OK" skips short/common names
#print STDERR scalar(@EXPORT_OK) . " consts exported:\n";
#foreach(@EXPORT_OK) { print STDERR "$_\n"; }
#my $val = main::thing("xyz");
#print STDERR "caller gave me $val\n";
#foreach my $arg (@ARGV) { print STDERR "arg $arg\n"; }
Author: swannman
Source Code: https://github.com/swannman/pdf2gerb
License: GPL-3.0 license
1620729846
Can you use WordPress for anything other than blogging? To your surprise, yes. WordPress is more than just a blogging tool, and it has helped thousands of websites and web applications to thrive. The use of WordPress powers around 40% of online projects, and today in our blog, we would visit some amazing uses of WordPress other than blogging.
What Is The Use Of WordPress?
WordPress is the most popular website platform in the world. It is the first choice of businesses that want to set a feature-rich and dynamic Content Management System. So, if you ask what WordPress is used for, the answer is – everything. It is a super-flexible, feature-rich and secure platform that offers everything to build unique websites and applications. Let’s start knowing them:
1. Multiple Websites Under A Single Installation
WordPress Multisite allows you to develop multiple sites from a single WordPress installation. You can download WordPress and start building websites you want to launch under a single server. Literally speaking, you can handle hundreds of sites from one single dashboard, which now needs applause.
It is a highly efficient platform that allows you to easily run several websites under the same login credentials. One of the best things about WordPress is the themes it has to offer. You can simply download them and plugin for various sites and save space on sites without losing their speed.
2. WordPress Social Network
WordPress can be used for high-end projects such as Social Media Network. If you don’t have the money and patience to hire a coder and invest months in building a feature-rich social media site, go for WordPress. It is one of the most amazing uses of WordPress. Its stunning CMS is unbeatable. And you can build sites as good as Facebook or Reddit etc. It can just make the process a lot easier.
To set up a social media network, you would have to download a WordPress Plugin called BuddyPress. It would allow you to connect a community page with ease and would provide all the necessary features of a community or social media. It has direct messaging, activity stream, user groups, extended profiles, and so much more. You just have to download and configure it.
If BuddyPress doesn’t meet all your needs, don’t give up on your dreams. You can try out WP Symposium or PeepSo. There are also several themes you can use to build a social network.
3. Create A Forum For Your Brand’s Community
Communities are very important for your business. They help you stay in constant connection with your users and consumers. And allow you to turn them into a loyal customer base. Meanwhile, there are many good technologies that can be used for building a community page – the good old WordPress is still the best.
It is the best community development technology. If you want to build your online community, you need to consider all the amazing features you get with WordPress. Plugins such as BB Press is an open-source, template-driven PHP/ MySQL forum software. It is very simple and doesn’t hamper the experience of the website.
Other tools such as wpFoRo and Asgaros Forum are equally good for creating a community blog. They are lightweight tools that are easy to manage and integrate with your WordPress site easily. However, there is only one tiny problem; you need to have some technical knowledge to build a WordPress Community blog page.
4. Shortcodes
Since we gave you a problem in the previous section, we would also give you a perfect solution for it. You might not know to code, but you have shortcodes. Shortcodes help you execute functions without having to code. It is an easy way to build an amazing website, add new features, customize plugins easily. They are short lines of code, and rather than memorizing multiple lines; you can have zero technical knowledge and start building a feature-rich website or application.
There are also plugins like Shortcoder, Shortcodes Ultimate, and the Basics available on WordPress that can be used, and you would not even have to remember the shortcodes.
5. Build Online Stores
If you still think about why to use WordPress, use it to build an online store. You can start selling your goods online and start selling. It is an affordable technology that helps you build a feature-rich eCommerce store with WordPress.
WooCommerce is an extension of WordPress and is one of the most used eCommerce solutions. WooCommerce holds a 28% share of the global market and is one of the best ways to set up an online store. It allows you to build user-friendly and professional online stores and has thousands of free and paid extensions. Moreover as an open-source platform, and you don’t have to pay for the license.
Apart from WooCommerce, there are Easy Digital Downloads, iThemes Exchange, Shopify eCommerce plugin, and so much more available.
6. Security Features
WordPress takes security very seriously. It offers tons of external solutions that help you in safeguarding your WordPress site. While there is no way to ensure 100% security, it provides regular updates with security patches and provides several plugins to help with backups, two-factor authorization, and more.
By choosing hosting providers like WP Engine, you can improve the security of the website. It helps in threat detection, manage patching and updates, and internal security audits for the customers, and so much more.
#use of wordpress #use wordpress for business website #use wordpress for website #what is use of wordpress #why use wordpress #why use wordpress to build a website
1641430440
Pandas-Bokeh provides a Bokeh plotting backend for Pandas, GeoPandas and Pyspark DataFrames, similar to the already existing Visualization feature of Pandas. Importing the library adds a complementary plotting method plot_bokeh() on DataFrames and Series.
With Pandas-Bokeh, creating stunning, interactive, HTML-based visualization is as easy as calling:
df.plot_bokeh()
Pandas-Bokeh also provides native support as a Pandas Plotting backend for Pandas >= 0.25. When Pandas-Bokeh is installed, switchting the default Pandas plotting backend to Bokeh can be done via:
pd.set_option('plotting.backend', 'pandas_bokeh')
More details about the new Pandas backend can be found below.
Please visit:
https://patrikhlobil.github.io/Pandas-Bokeh/
for an interactive version of the documentation below, where you can play with the dynamic Bokeh plots.
For more information have a look at the Examples below or at notebooks on the Github Repository of this project.
You can install Pandas-Bokeh from PyPI via pip
pip install pandas-bokeh
or conda:
conda install -c patrikhlobil pandas-bokeh
With the current release 0.5.5, Pandas-Bokeh officially supports Python 3.6 and newer. For more details, see Release Notes.
The Pandas-Bokeh library should be imported after Pandas, GeoPandas and/or Pyspark. After the import, one should define the plotting output, which can be:
pandas_bokeh.output_notebook(): Embeds the Plots in the cell outputs of the notebook. Ideal when working in Jupyter Notebooks.
pandas_bokeh.output_file(filename): Exports the plot to the provided filename as an HTML.
For more details about the plotting outputs, see the reference here or the Bokeh documentation.
import pandas as pd import pandas_bokeh pandas_bokeh.output_notebook()
import pandas as pd import pandas_bokeh pandas_bokeh.output_file("Interactive Plot.html")
For pandas >= 0.25, a plotting backend switch is natively supported. It can be achievied by calling:
import pandas as pd
pd.set_option('plotting.backend', 'pandas_bokeh')
Now, the plotting API is accessible for a Pandas DataFrame via:
df.plot(...)
All additional functionalities of Pandas-Bokeh are then accessible at pd.plotting. So, setting the output to notebook is:
pd.plotting.output_notebook()
or calling the grid layout functionality:
pd.plotting.plot_grid(...)
Note: Backwards compatibility is kept since there will still be the df.plot_bokeh(...) methods for a DataFrame.
Supported plottypes are at the moment:
Also, check out the complementary chapter Outputs, Formatting & Layouts about:
This simple lineplot in Pandas-Bokeh already contains various interactive elements:
Consider the following simple example:
import numpy as np
np.random.seed(42)
df = pd.DataFrame({"Google": np.random.randn(1000)+0.2,
"Apple": np.random.randn(1000)+0.17},
index=pd.date_range('1/1/2000', periods=1000))
df = df.cumsum()
df = df + 50
df.plot_bokeh(kind="line") #equivalent to df.plot_bokeh.line()
Note, that similar to the regular pandas.DataFrame.plot method, there are also additional accessors to directly access the different plotting types like:
df.plot_bokeh(kind="line", ...)
→ df.plot_bokeh.line(...)
df.plot_bokeh(kind="bar", ...)
→ df.plot_bokeh.bar(...)
df.plot_bokeh(kind="hist", ...)
→ df.plot_bokeh.hist(...)
There are various optional parameters to tune the plots, for example:
kind: Which kind of plot should be produced. Currently supported are: "line", "point", "scatter", "bar" and "histogram". In the near future many more will be implemented as horizontal barplot, boxplots, pie-charts, etc.
x: Name of the column to use for the horizontal x-axis. If the x parameter is not specified, the index is used for the x-values of the plot. Alternative, also an array of values can be passed that has the same number of elements as the DataFrame.
y: Name of column or list of names of columns to use for the vertical y-axis.
figsize: Choose width & height of the plot
title: Sets title of the plot
xlim/ylim: Set visibler range of plot for x- and y-axis (also works for datetime x-axis)
xlabel/ylabel: Set x- and y-labels
logx/logy: Set log-scale on x-/y-axis
xticks/yticks: Explicitly set the ticks on the axes
color: Defines a single color for a plot.
colormap: Can be used to specify multiple colors to plot. Can be either a list of colors or the name of a Bokeh color palette
hovertool: If True a Hovertool is active, else if False no Hovertool is drawn.
hovertool_string: If specified, this string will be used for the hovertool (@{column} will be replaced by the value of the column for the element the mouse hovers over, see also Bokeh documentation and here)
toolbar_location: Specify the position of the toolbar location (None, "above", "below", "left" or "right"). Default: "right"
zooming: Enables/Disables zooming. Default: True
panning: Enables/Disables panning. Default: True
fontsize_label/fontsize_ticks/fontsize_title/fontsize_legend: Set fontsize of labels, ticks, title or legend (int or string of form "15pt")
rangetool Enables a range tool scroller. Default False
kwargs**: Optional keyword arguments of bokeh.plotting.figure.line
Try them out to get a feeling for the effects. Let us consider now:
df.plot_bokeh.line(
figsize=(800, 450),
y="Apple",
title="Apple vs Google",
xlabel="Date",
ylabel="Stock price [$]",
yticks=[0, 100, 200, 300, 400],
ylim=(0, 400),
toolbar_location=None,
colormap=["red", "blue"],
hovertool_string=r"""<img
src='https://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Apple_logo_black.svg/170px-Apple_logo_black.svg.png'
height="42" alt="@imgs" width="42"
style="float: left; margin: 0px 15px 15px 0px;"
border="2"></img> Apple
<h4> Stock Price: </h4> @{Apple}""",
panning=False,
zooming=False)
For lineplots, as for many other plot-kinds, there are some special keyword arguments that only work for this plotting type. For lineplots, these are:
plot_data_points: Plot also the data points on the lines
plot_data_points_size: Determines the size of the data points
marker: Defines the point type (Default: "circle"). Possible values are: 'circle', 'square', 'triangle', 'asterisk', 'circle_x', 'square_x', 'inverted_triangle', 'x', 'circle_cross', 'square_cross', 'diamond', 'cross'
kwargs**: Optional keyword arguments of bokeh.plotting.figure.line```
Let us use this information to have another version of the same plot:
df.plot_bokeh.line(
figsize=(800, 450),
title="Apple vs Google",
xlabel="Date",
ylabel="Stock price [$]",
yticks=[0, 100, 200, 300, 400],
ylim=(100, 200),
xlim=("2001-01-01", "2001-02-01"),
colormap=["red", "blue"],
plot_data_points=True,
plot_data_points_size=10,
marker="asterisk")
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD'))
df = df.cumsum()
df.plot_bokeh(rangetool=True)
Pointplot
If you just wish to draw the date points for curves, the pointplot option is the right choice. It also accepts the kwargs of bokeh.plotting.figure.scatter like marker or size:
import numpy as np
x = np.arange(-3, 3, 0.1)
y2 = x**2
y3 = x**3
df = pd.DataFrame({"x": x, "Parabula": y2, "Cube": y3})
df.plot_bokeh.point(
x="x",
xticks=range(-3, 4),
size=5,
colormap=["#009933", "#ff3399"],
title="Pointplot (Parabula vs. Cube)",
marker="x")
With a similar API as the line- & pointplots, one can generate a stepplot. Additional keyword arguments for this plot type are passes to bokeh.plotting.figure.step, e.g. mode (before, after, center), see the following example
import numpy as np
x = np.arange(-3, 3, 1)
y2 = x**2
y3 = x**3
df = pd.DataFrame({"x": x, "Parabula": y2, "Cube": y3})
df.plot_bokeh.step(
x="x",
xticks=range(-1, 1),
colormap=["#009933", "#ff3399"],
title="Pointplot (Parabula vs. Cube)",
figsize=(800,300),
fontsize_title=30,
fontsize_label=25,
fontsize_ticks=15,
fontsize_legend=5,
)
df.plot_bokeh.step(
x="x",
xticks=range(-1, 1),
colormap=["#009933", "#ff3399"],
title="Pointplot (Parabula vs. Cube)",
mode="after",
figsize=(800,300)
)
Note that the step-plot API of Bokeh does so far not support a hovertool functionality.
A basic scatterplot can be created using the kind="scatter" option. For scatterplots, the x and y parameters have to be specified and the following optional keyword argument is allowed:
category: Determines the category column to use for coloring the scatter points
kwargs**: Optional keyword arguments of bokeh.plotting.figure.scatter
Note, that the pandas.DataFrame.plot_bokeh() method return per default a Bokeh figure, which can be embedded in Dashboard layouts with other figures and Bokeh objects (for more details about (sub)plot layouts and embedding the resulting Bokeh plots as HTML click here).
In the example below, we use the building grid layout support of Pandas-Bokeh to display both the DataFrame (using a Bokeh DataTable) and the resulting scatterplot:
# Load Iris Dataset:
df = pd.read_csv(
r"https://raw.githubusercontent.com/PatrikHlobil/Pandas-Bokeh/master/docs/Testdata/iris/iris.csv"
)
df = df.sample(frac=1)
# Create Bokeh-Table with DataFrame:
from bokeh.models.widgets import DataTable, TableColumn
from bokeh.models import ColumnDataSource
data_table = DataTable(
columns=[TableColumn(field=Ci, title=Ci) for Ci in df.columns],
source=ColumnDataSource(df),
height=300,
)
# Create Scatterplot:
p_scatter = df.plot_bokeh.scatter(
x="petal length (cm)",
y="sepal width (cm)",
category="species",
title="Iris DataSet Visualization",
show_figure=False,
)
# Combine Table and Scatterplot via grid layout:
pandas_bokeh.plot_grid([[data_table, p_scatter]], plot_width=400, plot_height=350)
A possible optional keyword parameters that can be passed to bokeh.plotting.figure.scatter is size. Below, we use the sepal length of the Iris data as reference for the size:
#Change one value to clearly see the effect of the size keyword
df.loc[13, "sepal length (cm)"] = 15
#Make scatterplot:
p_scatter = df.plot_bokeh.scatter(
x="petal length (cm)",
y="sepal width (cm)",
category="species",
title="Iris DataSet Visualization with Size Keyword",
size="sepal length (cm)")
In this example you can see, that the additional dimension sepal length cannot be used to clearly differentiate between the virginica and versicolor species.
The barplot API has no special keyword arguments, but accepts optional kwargs of bokeh.plotting.figure.vbar like alpha. It uses per default the index for the bar categories (however, also columns can be used as x-axis category using the x argument).
data = {
'fruits':
['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries'],
'2015': [2, 1, 4, 3, 2, 4],
'2016': [5, 3, 3, 2, 4, 6],
'2017': [3, 2, 4, 4, 5, 3]
}
df = pd.DataFrame(data).set_index("fruits")
p_bar = df.plot_bokeh.bar(
ylabel="Price per Unit [€]",
title="Fruit prices per Year",
alpha=0.6)
Using the stacked keyword argument you also maked stacked barplots:
p_stacked_bar = df.plot_bokeh.bar(
ylabel="Price per Unit [€]",
title="Fruit prices per Year",
stacked=True,
alpha=0.6)
Also horizontal versions of the above barplot are supported with the keyword kind="barh" or the accessor plot_bokeh.barh. You can still specify a column of the DataFrame as the bar category via the x argument if you do not wish to use the index.
#Reset index, such that "fruits" is now a column of the DataFrame:
df.reset_index(inplace=True)
#Create horizontal bar (via kind keyword):
p_hbar = df.plot_bokeh(
kind="barh",
x="fruits",
xlabel="Price per Unit [€]",
title="Fruit prices per Year",
alpha=0.6,
legend = "bottom_right",
show_figure=False)
#Create stacked horizontal bar (via barh accessor):
p_stacked_hbar = df.plot_bokeh.barh(
x="fruits",
stacked=True,
xlabel="Price per Unit [€]",
title="Fruit prices per Year",
alpha=0.6,
legend = "bottom_right",
show_figure=False)
#Plot all barplot examples in a grid:
pandas_bokeh.plot_grid([[p_bar, p_stacked_bar],
[p_hbar, p_stacked_hbar]],
plot_width=450)
For drawing histograms (kind="hist"), Pandas-Bokeh has a lot of customization features. Optional keyword arguments for histogram plots are:
bins: Determines bins to use for the histogram. If bins is an int, it defines the number of equal-width bins in the given range (10, by default). If bins is a sequence, it defines the bin edges, including the rightmost edge, allowing for non-uniform bin widths. If bins is a string, it defines the method used to calculate the optimal bin width, as defined by histogram_bin_edges.
histogram_type: Either "sidebyside", "topontop" or "stacked". Default: "topontop"
stacked: Boolean that overrides the histogram_type as "stacked" if given. Default: False
kwargs**: Optional keyword arguments of bokeh.plotting.figure.quad
Below examples of the different histogram types:
import numpy as np
df_hist = pd.DataFrame({
'a': np.random.randn(1000) + 1,
'b': np.random.randn(1000),
'c': np.random.randn(1000) - 1
},
columns=['a', 'b', 'c'])
#Top-on-Top Histogram (Default):
df_hist.plot_bokeh.hist(
bins=np.linspace(-5, 5, 41),
vertical_xlabel=True,
hovertool=False,
title="Normal distributions (Top-on-Top)",
line_color="black")
#Side-by-Side Histogram (multiple bars share bin side-by-side) also accessible via
#kind="hist":
df_hist.plot_bokeh(
kind="hist",
bins=np.linspace(-5, 5, 41),
histogram_type="sidebyside",
vertical_xlabel=True,
hovertool=False,
title="Normal distributions (Side-by-Side)",
line_color="black")
#Stacked histogram:
df_hist.plot_bokeh.hist(
bins=np.linspace(-5, 5, 41),
histogram_type="stacked",
vertical_xlabel=True,
hovertool=False,
title="Normal distributions (Stacked)",
line_color="black")
Further, advanced keyword arguments for histograms are:
Their usage is shown in these examples:
p_hist = df_hist.plot_bokeh.hist(
y=["a", "b"],
bins=np.arange(-4, 6.5, 0.5),
normed=100,
vertical_xlabel=True,
ylabel="Share[%]",
title="Normal distributions (normed)",
show_average=True,
xlim=(-4, 6),
ylim=(0, 30),
show_figure=False)
p_hist_cum = df_hist.plot_bokeh.hist(
y=["a", "b"],
bins=np.arange(-4, 6.5, 0.5),
normed=100,
cumulative=True,
vertical_xlabel=True,
ylabel="Share[%]",
title="Normal distributions (normed & cumulative)",
show_figure=False)
pandas_bokeh.plot_grid([[p_hist, p_hist_cum]], plot_width=450, plot_height=300)
Areaplot (kind="area") can be either drawn on top of each other or stacked. The important parameters are:
stacked: If True, the areaplots are stacked. If False, plots are drawn on top of each other. Default: False
kwargs**: Optional keyword arguments of bokeh.plotting.figure.patch
Let us consider the energy consumption split by source that can be downloaded as DataFrame via:
df_energy = pd.read_csv(r"https://raw.githubusercontent.com/PatrikHlobil/Pandas-Bokeh/master/docs/Testdata/energy/energy.csv",
parse_dates=["Year"])
df_energy.head()
Year | Oil | Gas | Coal | Nuclear Energy | Hydroelectricity | Other Renewable |
---|---|---|---|---|---|---|
1970-01-01 | 2291.5 | 826.7 | 1467.3 | 17.7 | 265.8 | 5.8 |
1971-01-01 | 2427.7 | 884.8 | 1459.2 | 24.9 | 276.4 | 6.3 |
1972-01-01 | 2613.9 | 933.7 | 1475.7 | 34.1 | 288.9 | 6.8 |
1973-01-01 | 2818.1 | 978.0 | 1519.6 | 45.9 | 292.5 | 7.3 |
1974-01-01 | 2777.3 | 1001.9 | 1520.9 | 59.6 | 321.1 | 7.7 |
Creating the Areaplot can be achieved via:
df_energy.plot_bokeh.area(
x="Year",
stacked=True,
legend="top_left",
colormap=["brown", "orange", "black", "grey", "blue", "green"],
title="Worldwide energy consumption split by energy source",
ylabel="Million tonnes oil equivalent",
ylim=(0, 16000))
Note that the energy consumption of fossile energy is still increasing and renewable energy sources are still small in comparison 😢!!! However, when we norm the plot using the normed keyword, there is a clear trend towards renewable energies in the last decade:
df_energy.plot_bokeh.area(
x="Year",
stacked=True,
normed=100,
legend="bottom_left",
colormap=["brown", "orange", "black", "grey", "blue", "green"],
title="Worldwide energy consumption split by energy source",
ylabel="Million tonnes oil equivalent")
Pieplot
For Pieplots, let us consider a dataset showing the results of all Bundestags elections in Germany since 2002:
df_pie = pd.read_csv(r"https://raw.githubusercontent.com/PatrikHlobil/Pandas-Bokeh/master/docs/Testdata/Bundestagswahl/Bundestagswahl.csv")
df_pie
Partei | 2002 | 2005 | 2009 | 2013 | 2017 |
---|---|---|---|---|---|
CDU/CSU | 38.5 | 35.2 | 33.8 | 41.5 | 32.9 |
SPD | 38.5 | 34.2 | 23.0 | 25.7 | 20.5 |
FDP | 7.4 | 9.8 | 14.6 | 4.8 | 10.7 |
Grünen | 8.6 | 8.1 | 10.7 | 8.4 | 8.9 |
Linke/PDS | 4.0 | 8.7 | 11.9 | 8.6 | 9.2 |
AfD | 0.0 | 0.0 | 0.0 | 0.0 | 12.6 |
Sonstige | 3.0 | 4.0 | 6.0 | 11.0 | 5.0 |
We can create a Pieplot of the last election in 2017 by specifying the "Partei" (german for party) column as the x column and the "2017" column as the y column for values:
df_pie.plot_bokeh.pie(
x="Partei",
y="2017",
colormap=["blue", "red", "yellow", "green", "purple", "orange", "grey"],
title="Results of German Bundestag Election 2017",
)
When you pass several columns to the y parameter (not providing the y-parameter assumes you plot all columns), multiple nested pieplots will be shown in one plot:
df_pie.plot_bokeh.pie(
x="Partei",
colormap=["blue", "red", "yellow", "green", "purple", "orange", "grey"],
title="Results of German Bundestag Elections [2002-2017]",
line_color="grey")
Mapplot
The mapplot method of Pandas-Bokeh allows for plotting geographic points stored in a Pandas DataFrame on an interactive map. For more advanced Geoplots for line and polygon shapes have a look at the Geoplots examples for the GeoPandas API of Pandas-Bokeh.
For mapplots, only (latitude, longitude) pairs in geographic projection (WGS84) can be plotted on a map. The basic API has the following 2 base parameters:
The other optional keyword arguments are discussed in the section about the GeoPandas API, e.g. category for coloring the points.
Below an example of plotting all cities for more than 1 million inhabitants:
df_mapplot = pd.read_csv(r"https://raw.githubusercontent.com/PatrikHlobil/Pandas-Bokeh/master/docs/Testdata/populated%20places/populated_places.csv")
df_mapplot.head()
name | pop_max | latitude | longitude | size |
---|---|---|---|---|
Mesa | 1085394 | 33.423915 | -111.736084 | 1.085394 |
Sharjah | 1103027 | 25.371383 | 55.406478 | 1.103027 |
Changwon | 1081499 | 35.219102 | 128.583562 | 1.081499 |
Sheffield | 1292900 | 53.366677 | -1.499997 | 1.292900 |
Abbottabad | 1183647 | 34.149503 | 73.199501 | 1.183647 |
df_mapplot["size"] = df_mapplot["pop_max"] / 1000000
df_mapplot.plot_bokeh.map(
x="longitude",
y="latitude",
hovertool_string="""<h2> @{name} </h2>
<h3> Population: @{pop_max} </h3>""",
tile_provider="STAMEN_TERRAIN_RETINA",
size="size",
figsize=(900, 600),
title="World cities with more than 1.000.000 inhabitants")
Pandas-Bokeh also allows for interactive plotting of Maps using GeoPandas by providing a geopandas.GeoDataFrame.plot_bokeh() method. It allows to plot the following geodata on a map :
Note: t is not possible to mix up the objects types, i.e. a GeoDataFrame with Points and Lines is for example not allowed.
Les us start with a simple example using the "World Borders Dataset" . Let us first import all neccessary libraries and read the shapefile:
import geopandas as gpd
import pandas as pd
import pandas_bokeh
pandas_bokeh.output_notebook()
#Read in GeoJSON from URL:
df_states = gpd.read_file(r"https://raw.githubusercontent.com/PatrikHlobil/Pandas-Bokeh/master/docs/Testdata/states/states.geojson")
df_states.head()
STATE_NAME | REGION | POPESTIMATE2010 | POPESTIMATE2011 | POPESTIMATE2012 | POPESTIMATE2013 | POPESTIMATE2014 | POPESTIMATE2015 | POPESTIMATE2016 | POPESTIMATE2017 | geometry |
---|---|---|---|---|---|---|---|---|---|---|
Hawaii | 4 | 1363817 | 1378323 | 1392772 | 1408038 | 1417710 | 1426320 | 1428683 | 1427538 | (POLYGON ((-160.0738033454681 22.0041773479577... |
Washington | 4 | 6741386 | 6819155 | 6890899 | 6963410 | 7046931 | 7152818 | 7280934 | 7405743 | (POLYGON ((-122.4020153103835 48.2252163723779... |
Montana | 4 | 990507 | 996866 | 1003522 | 1011921 | 1019931 | 1028317 | 1038656 | 1050493 | POLYGON ((-111.4754253002074 44.70216236909688... |
Maine | 1 | 1327568 | 1327968 | 1328101 | 1327975 | 1328903 | 1327787 | 1330232 | 1335907 | (POLYGON ((-69.77727626137293 44.0741483685119... |
North Dakota | 2 | 674518 | 684830 | 701380 | 722908 | 738658 | 754859 | 755548 | 755393 | POLYGON ((-98.73043728833767 45.93827137024809... |
Plotting the data on a map is as simple as calling:
df_states.plot_bokeh(simplify_shapes=10000)
We also passed the optional parameter simplify_shapes (~meter) to improve plotting performance (for a reference see shapely.object.simplify). The above geolayer thus has an accuracy of about 10km.
Many keyword arguments like xlabel, ylabel, xlim, ylim, title, colormap, hovertool, zooming, panning, ... for costumizing the plot are also available for the geoplotting API and can be uses as in the examples shown above. There are however also many other options especially for plotting geodata:
One of the most common usage of map plots are choropleth maps, where the color of a the objects is determined by the property of the object itself. There are 3 ways of drawing choropleth maps using Pandas-Bokeh, which are described below.
This is the simplest way. Just provide the category keyword for the selection of the property column:
Let us now draw the regions as a choropleth plot using the category keyword (at the moment, only numerical columns are supported for choropleth plots):
df_states.plot_bokeh(
figsize=(900, 600),
simplify_shapes=5000,
category="REGION",
show_colorbar=False,
colormap=["blue", "yellow", "green", "red"],
hovertool_columns=["STATE_NAME", "REGION"],
tile_provider="STAMEN_TERRAIN_RETINA")
When hovering over the states, the state-name and the region are shown as specified in the hovertool_columns argument.
By passing a list of column names of the GeoDataFrame as the dropdown keyword argument, a dropdown menu is shown above the map. This dropdown menu can be used to select the choropleth layer by the user. :
df_states["STATE_NAME_SMALL"] = df_states["STATE_NAME"].str.lower()
df_states.plot_bokeh(
figsize=(900, 600),
simplify_shapes=5000,
dropdown=["POPESTIMATE2010", "POPESTIMATE2017"],
colormap="Viridis",
hovertool_string="""
<img
src="https://www.states101.com/img/flags/gif/small/@STATE_NAME_SMALL.gif"
height="42" alt="@imgs" width="42"
style="float: left; margin: 0px 15px 15px 0px;"
border="2"></img>
<h2> @STATE_NAME </h2>
<h3> 2010: @POPESTIMATE2010 </h3>
<h3> 2017: @POPESTIMATE2017 </h3>""",
tile_provider_url=r"http://c.tile.stamen.com/watercolor/{Z}/{X}/{Y}.jpg",
tile_attribution='Map tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>. Data by <a href="http://openstreetmap.org">OpenStreetMap</a>, under <a href="http://www.openstreetmap.org/copyright">ODbL</a>.'
)
Using hovertool_string, one can pass a string that can contain arbitrary HTML elements (including divs, images, ...) that is shown when hovering over the geographies (@{column} will be replaced by the value of the column for the element the mouse hovers over, see also Bokeh documentation).
Here, we also used an OSM tile server with watercolor style via tile_provider_url and added the attribution via tile_attribution.
Another option for interactive choropleth maps is the slider implementation of Pandas-Bokeh. The possible keyword arguments are here:
This can be used to display the change in population relative to the year 2010:
#Calculate change of population relative to 2010:
for i in range(8):
df_states["Delta_Population_201%d"%i] = ((df_states["POPESTIMATE201%d"%i] / df_states["POPESTIMATE2010"]) -1 ) * 100
#Specify slider columns:
slider_columns = ["Delta_Population_201%d"%i for i in range(8)]
#Specify slider-range (Maps "Delta_Population_2010" -> 2010,
# "Delta_Population_2011" -> 2011, ...):
slider_range = range(2010, 2018)
#Make slider plot:
df_states.plot_bokeh(
figsize=(900, 600),
simplify_shapes=5000,
slider=slider_columns,
slider_range=slider_range,
slider_name="Year",
colormap="Inferno",
hovertool_columns=["STATE_NAME"] + slider_columns,
title="Change of Population [%]")
If you wish to display multiple geolayers, you can pass the Bokeh figure of a Pandas-Bokeh plot via the figure keyword to the next plot_bokeh() call:
import geopandas as gpd
import pandas_bokeh
pandas_bokeh.output_notebook()
# Read in GeoJSONs from URL:
df_states = gpd.read_file(r"https://raw.githubusercontent.com/PatrikHlobil/Pandas-Bokeh/master/docs/Testdata/states/states.geojson")
df_cities = gpd.read_file(
r"https://raw.githubusercontent.com/PatrikHlobil/Pandas-Bokeh/master/docs/Testdata/populated%20places/ne_10m_populated_places_simple_bigcities.geojson"
)
df_cities["size"] = df_cities.pop_max / 400000
#Plot shapes of US states (pass figure options to this initial plot):
figure = df_states.plot_bokeh(
figsize=(800, 450),
simplify_shapes=10000,
show_figure=False,
xlim=[-170, -80],
ylim=[10, 70],
category="REGION",
colormap="Dark2",
legend="States",
show_colorbar=False,
)
#Plot cities as points on top of the US states layer by passing the figure:
df_cities.plot_bokeh(
figure=figure, # <== pass figure here!
category="pop_max",
colormap="Viridis",
colormap_uselog=True,
size="size",
hovertool_string="""<h1>@name</h1>
<h3>Population: @pop_max </h3>""",
marker="inverted_triangle",
legend="Cities",
)
Below, you can see an example that use Pandas-Bokeh to plot point data on a map. The plot shows all cities with a population larger than 1.000.000. For point plots, you can select the marker as keyword argument (since it is passed to bokeh.plotting.figure.scatter). Here an overview of all available marker types:
gdf = gpd.read_file(r"https://raw.githubusercontent.com/PatrikHlobil/Pandas-Bokeh/master/docs/Testdata/populated%20places/ne_10m_populated_places_simple_bigcities.geojson")
gdf["size"] = gdf.pop_max / 400000
gdf.plot_bokeh(
category="pop_max",
colormap="Viridis",
colormap_uselog=True,
size="size",
hovertool_string="""<h1>@name</h1>
<h3>Population: @pop_max </h3>""",
xlim=[-15, 35],
ylim=[30,60],
marker="inverted_triangle");
In a similar way, also GeoDataFrames with (multi)line shapes can be drawn using Pandas-Bokeh.
If you want to display the numerical labels on your colorbar with an alternative to the scientific format, you can pass in a one of the bokeh number string formats or an instance of one of the bokeh.models.formatters to the colorbar_tick_format
argument in the geoplot
An example of using the string format argument:
df_states = gpd.read_file(r"https://raw.githubusercontent.com/PatrikHlobil/Pandas-Bokeh/master/docs/Testdata/states/states.geojson")
df_states["STATE_NAME_SMALL"] = df_states["STATE_NAME"].str.lower()
# pass in a string format to colorbar_tick_format to display the ticks as 10m rather than 1e7
df_states.plot_bokeh(
figsize=(900, 600),
category="POPESTIMATE2017",
simplify_shapes=5000,
colormap="Inferno",
colormap_uselog=True,
colorbar_tick_format="0.0a")
An example of using the bokeh PrintfTickFormatter
:
df_states = gpd.read_file(r"https://raw.githubusercontent.com/PatrikHlobil/Pandas-Bokeh/master/docs/Testdata/states/states.geojson")
df_states["STATE_NAME_SMALL"] = df_states["STATE_NAME"].str.lower()
for i in range(8):
df_states["Delta_Population_201%d"%i] = ((df_states["POPESTIMATE201%d"%i] / df_states["POPESTIMATE2010"]) -1 ) * 100
# pass in a PrintfTickFormatter instance colorbar_tick_format to display the ticks with 2 decimal places
df_states.plot_bokeh(
figsize=(900, 600),
category="Delta_Population_2017",
simplify_shapes=5000,
colormap="Inferno",
colorbar_tick_format=PrintfTickFormatter(format="%4.2f"))
The pandas.DataFrame.plot_bokeh API has the following additional keyword arguments:
If you have a Bokeh figure or layout, you can also use the pandas_bokeh.embedded_html function to generate an embeddable HTML representation of the plot. This can be included into any valid HTML (note that this is not possible directly with the HTML generated by the pandas_bokeh.output_file output option, because it includes an HTML header). Let us consider the following simple example:
#Import Pandas and Pandas-Bokeh (if you do not specify an output option, the standard is
#output_file):
import pandas as pd
import pandas_bokeh
#Create DataFrame to Plot:
import numpy as np
x = np.arange(-10, 10, 0.1)
sin = np.sin(x)
cos = np.cos(x)
tan = np.tan(x)
df = pd.DataFrame({"x": x, "sin(x)": sin, "cos(x)": cos, "tan(x)": tan})
#Make Bokeh plot from DataFrame using Pandas-Bokeh. Do not show the plot, but export
#it to an embeddable HTML string:
html_plot = df.plot_bokeh(
kind="line",
x="x",
y=["sin(x)", "cos(x)", "tan(x)"],
xticks=range(-20, 20),
title="Trigonometric functions",
show_figure=False,
return_html=True,
ylim=(-1.5, 1.5))
#Write some HTML and embed the HTML plot below it. For production use, please use
#Templates and the awesome Jinja library.
html = r"""
<script type="text/x-mathjax-config">
MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}});
</script>
<script type="text/javascript"
src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<h1> Trigonometric functions </h1>
<p> The basic trigonometric functions are:</p>
<p>$ sin(x) $</p>
<p>$ cos(x) $</p>
<p>$ tan(x) = \frac{sin(x)}{cos(x)}$</p>
<p>Below is a plot that shows them</p>
""" + html_plot
#Export the HTML string to an external HTML file and show it:
with open("test.html" , "w") as f:
f.write(html)
import webbrowser
webbrowser.open("test.html")
This code will open up a webbrowser and show the following page. As you can see, the interactive Bokeh plot is embedded nicely into the HTML layout. The return_html option is ideal for the use in a templating engine like Jinja.
For single plots that have a number of x axis values or for larger monitors, you can auto scale the figure to the width of the entire jupyter cell by setting the sizing_mode
parameter.
df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd']) df.plot_bokeh(kind="bar", figsize=(500, 200), sizing_mode="scale_width")
The figsize
parameter can be used to change the height and width as well as act as a scaling multiplier against the axis that is not being scaled.
To change the formats of numbers in the hovertool, use the number_format keyword argument. For a documentation about the format to pass, have a look at the Bokeh documentation.Let us consider some examples for the number 3.141592653589793:
Format | Output |
---|---|
0 | 3 |
0.000 | 3.141 |
0.00 $ | 3.14 $ |
This number format will be applied to all numeric columns of the hovertool. If you want to make a very custom or complicated hovertool, you should probably use the hovertool_string keyword argument, see e.g. this example. Below, we use the number_format parameter to specify the "Stock Price" format to 2 decimal digits and an additional $ sign.
import numpy as np
#Lineplot:
np.random.seed(42)
df = pd.DataFrame({
"Google": np.random.randn(1000) + 0.2,
"Apple": np.random.randn(1000) + 0.17
},
index=pd.date_range('1/1/2000', periods=1000))
df = df.cumsum()
df = df + 50
df.plot_bokeh(
kind="line",
title="Apple vs Google",
xlabel="Date",
ylabel="Stock price [$]",
yticks=[0, 100, 200, 300, 400],
ylim=(0, 400),
colormap=["red", "blue"],
number_format="1.00 $")
If you want to suppress the scientific notation for axes, you can use the disable_scientific_axes parameter, which accepts one of "x", "y", "xy":
df = pd.DataFrame({"Animal": ["Mouse", "Rabbit", "Dog", "Tiger", "Elefant", "Wale"],
"Weight [g]": [19, 3000, 40000, 200000, 6000000, 50000000]})
p_scientific = df.plot_bokeh(x="Animal", y="Weight [g]", show_figure=False)
p_non_scientific = df.plot_bokeh(x="Animal", y="Weight [g]", disable_scientific_axes="y", show_figure=False,)
pandas_bokeh.plot_grid([[p_scientific, p_non_scientific]], plot_width = 450)
As shown in the Scatterplot Example, combining plots with plots or other HTML elements is straighforward in Pandas-Bokeh due to the layout capabilities of Bokeh. The easiest way to generate a dashboard layout is using the pandas_bokeh.plot_grid method (which is an extension of bokeh.layouts.gridplot):
import pandas as pd
import numpy as np
import pandas_bokeh
pandas_bokeh.output_notebook()
#Barplot:
data = {
'fruits':
['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries'],
'2015': [2, 1, 4, 3, 2, 4],
'2016': [5, 3, 3, 2, 4, 6],
'2017': [3, 2, 4, 4, 5, 3]
}
df = pd.DataFrame(data).set_index("fruits")
p_bar = df.plot_bokeh(
kind="bar",
ylabel="Price per Unit [€]",
title="Fruit prices per Year",
show_figure=False)
#Lineplot:
np.random.seed(42)
df = pd.DataFrame({
"Google": np.random.randn(1000) + 0.2,
"Apple": np.random.randn(1000) + 0.17
},
index=pd.date_range('1/1/2000', periods=1000))
df = df.cumsum()
df = df + 50
p_line = df.plot_bokeh(
kind="line",
title="Apple vs Google",
xlabel="Date",
ylabel="Stock price [$]",
yticks=[0, 100, 200, 300, 400],
ylim=(0, 400),
colormap=["red", "blue"],
show_figure=False)
#Scatterplot:
from sklearn.datasets import load_iris
iris = load_iris()
df = pd.DataFrame(iris["data"])
df.columns = iris["feature_names"]
df["species"] = iris["target"]
df["species"] = df["species"].map(dict(zip(range(3), iris["target_names"])))
p_scatter = df.plot_bokeh(
kind="scatter",
x="petal length (cm)",
y="sepal width (cm)",
category="species",
title="Iris DataSet Visualization",
show_figure=False)
#Histogram:
df_hist = pd.DataFrame({
'a': np.random.randn(1000) + 1,
'b': np.random.randn(1000),
'c': np.random.randn(1000) - 1
},
columns=['a', 'b', 'c'])
p_hist = df_hist.plot_bokeh(
kind="hist",
bins=np.arange(-6, 6.5, 0.5),
vertical_xlabel=True,
normed=100,
hovertool=False,
title="Normal distributions",
show_figure=False)
#Make Dashboard with Grid Layout:
pandas_bokeh.plot_grid([[p_line, p_bar],
[p_scatter, p_hist]], plot_width=450)
Using a combination of row and column elements (see also Bokeh Layouts) allow for a very easy general arrangement of elements. An alternative layout to the one above is:
p_line.plot_width = 900
p_hist.plot_width = 900
layout = pandas_bokeh.column(p_line,
pandas_bokeh.row(p_scatter, p_bar),
p_hist)
pandas_bokeh.show(layout)
Release Notes
Release Notes can be found here.
Contributing to Pandas-Bokeh
If you wish to contribute to the development of Pandas-Bokeh
you can follow the instructions on the CONTRIBUTING.md.
Author: PatrikHlobil
Source Code: https://github.com/PatrikHlobil/Pandas-Bokeh
License: MIT License
1642995900
Pandas-Bokeh provides a Bokeh plotting backend for Pandas, GeoPandas and Pyspark DataFrames, similar to the already existing Visualization feature of Pandas. Importing the library adds a complementary plotting method plot_bokeh() on DataFrames and Series.
With Pandas-Bokeh, creating stunning, interactive, HTML-based visualization is as easy as calling:
df.plot_bokeh()
Pandas-Bokeh also provides native support as a Pandas Plotting backend for Pandas >= 0.25. When Pandas-Bokeh is installed, switchting the default Pandas plotting backend to Bokeh can be done via:
pd.set_option('plotting.backend', 'pandas_bokeh')
More details about the new Pandas backend can be found below.
Please visit:
https://patrikhlobil.github.io/Pandas-Bokeh/
for an interactive version of the documentation below, where you can play with the dynamic Bokeh plots.
For more information have a look at the Examples below or at notebooks on the Github Repository of this project.
You can install Pandas-Bokeh from PyPI via pip
pip install pandas-bokeh
or conda:
conda install -c patrikhlobil pandas-bokeh
With the current release 0.5.5, Pandas-Bokeh officially supports Python 3.6 and newer. For more details, see Release Notes.
The Pandas-Bokeh library should be imported after Pandas, GeoPandas and/or Pyspark. After the import, one should define the plotting output, which can be:
For more details about the plotting outputs, see the reference here or the Bokeh documentation.
import pandas as pd
import pandas_bokeh
pandas_bokeh.output_notebook()
import pandas as pd
import pandas_bokeh
pandas_bokeh.output_file("Interactive Plot.html")
For pandas >= 0.25, a plotting backend switch is natively supported. It can be achievied by calling:
import pandas as pd
pd.set_option('plotting.backend', 'pandas_bokeh')
Now, the plotting API is accessible for a Pandas DataFrame via:
df.plot(...)
All additional functionalities of Pandas-Bokeh are then accessible at pd.plotting. So, setting the output to notebook is:
pd.plotting.output_notebook()
or calling the grid layout functionality:
pd.plotting.plot_grid(...)
Note: Backwards compatibility is kept since there will still be the df.plot_bokeh(...) methods for a DataFrame.
Supported plottypes are at the moment:
Also, check out the complementary chapter Outputs, Formatting & Layouts about:
This simple lineplot in Pandas-Bokeh already contains various interactive elements:
Consider the following simple example:
import numpy as np
np.random.seed(42)
df = pd.DataFrame({"Google": np.random.randn(1000)+0.2,
"Apple": np.random.randn(1000)+0.17},
index=pd.date_range('1/1/2000', periods=1000))
df = df.cumsum()
df = df + 50
df.plot_bokeh(kind="line") #equivalent to df.plot_bokeh.line()
Note, that similar to the regular pandas.DataFrame.plot method, there are also additional accessors to directly access the different plotting types like:
df.plot_bokeh(kind="line", ...)
→ df.plot_bokeh.line(...)
df.plot_bokeh(kind="bar", ...)
→ df.plot_bokeh.bar(...)
df.plot_bokeh(kind="hist", ...)
→ df.plot_bokeh.hist(...)
There are various optional parameters to tune the plots, for example:
Try them out to get a feeling for the effects. Let us consider now:
df.plot_bokeh.line(
figsize=(800, 450),
y="Apple",
title="Apple vs Google",
xlabel="Date",
ylabel="Stock price [$]",
yticks=[0, 100, 200, 300, 400],
ylim=(0, 400),
toolbar_location=None,
colormap=["red", "blue"],
hovertool_string=r"""<img
src='https://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Apple_logo_black.svg/170px-Apple_logo_black.svg.png'
height="42" alt="@imgs" width="42"
style="float: left; margin: 0px 15px 15px 0px;"
border="2"></img> Apple
<h4> Stock Price: </h4> @{Apple}""",
panning=False,
zooming=False)
For lineplots, as for many other plot-kinds, there are some special keyword arguments that only work for this plotting type. For lineplots, these are:
Let us use this information to have another version of the same plot:
df.plot_bokeh.line(
figsize=(800, 450),
title="Apple vs Google",
xlabel="Date",
ylabel="Stock price [$]",
yticks=[0, 100, 200, 300, 400],
ylim=(100, 200),
xlim=("2001-01-01", "2001-02-01"),
colormap=["red", "blue"],
plot_data_points=True,
plot_data_points_size=10,
marker="asterisk")
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD'))
df = df.cumsum()
df.plot_bokeh(rangetool=True)
If you just wish to draw the date points for curves, the pointplot option is the right choice. It also accepts the kwargs of bokeh.plotting.figure.scatter like marker or size:
import numpy as np
x = np.arange(-3, 3, 0.1)
y2 = x**2
y3 = x**3
df = pd.DataFrame({"x": x, "Parabula": y2, "Cube": y3})
df.plot_bokeh.point(
x="x",
xticks=range(-3, 4),
size=5,
colormap=["#009933", "#ff3399"],
title="Pointplot (Parabula vs. Cube)",
marker="x")
With a similar API as the line- & pointplots, one can generate a stepplot. Additional keyword arguments for this plot type are passes to bokeh.plotting.figure.step, e.g. mode (before, after, center), see the following example
import numpy as np
x = np.arange(-3, 3, 1)
y2 = x**2
y3 = x**3
df = pd.DataFrame({"x": x, "Parabula": y2, "Cube": y3})
df.plot_bokeh.step(
x="x",
xticks=range(-1, 1),
colormap=["#009933", "#ff3399"],
title="Pointplot (Parabula vs. Cube)",
figsize=(800,300),
fontsize_title=30,
fontsize_label=25,
fontsize_ticks=15,
fontsize_legend=5,
)
df.plot_bokeh.step(
x="x",
xticks=range(-1, 1),
colormap=["#009933", "#ff3399"],
title="Pointplot (Parabula vs. Cube)",
mode="after",
figsize=(800,300)
)
Note that the step-plot API of Bokeh does so far not support a hovertool functionality.
A basic scatterplot can be created using the kind="scatter" option. For scatterplots, the x and y parameters have to be specified and the following optional keyword argument is allowed:
category: Determines the category column to use for coloring the scatter points
kwargs**: Optional keyword arguments of bokeh.plotting.figure.scatter
Note, that the pandas.DataFrame.plot_bokeh() method return per default a Bokeh figure, which can be embedded in Dashboard layouts with other figures and Bokeh objects (for more details about (sub)plot layouts and embedding the resulting Bokeh plots as HTML click here).
In the example below, we use the building grid layout support of Pandas-Bokeh to display both the DataFrame (using a Bokeh DataTable) and the resulting scatterplot:
# Load Iris Dataset:
df = pd.read_csv(
r"https://raw.githubusercontent.com/PatrikHlobil/Pandas-Bokeh/master/docs/Testdata/iris/iris.csv"
)
df = df.sample(frac=1)
# Create Bokeh-Table with DataFrame:
from bokeh.models.widgets import DataTable, TableColumn
from bokeh.models import ColumnDataSource
data_table = DataTable(
columns=[TableColumn(field=Ci, title=Ci) for Ci in df.columns],
source=ColumnDataSource(df),
height=300,
)
# Create Scatterplot:
p_scatter = df.plot_bokeh.scatter(
x="petal length (cm)",
y="sepal width (cm)",
category="species",
title="Iris DataSet Visualization",
show_figure=False,
)
# Combine Table and Scatterplot via grid layout:
pandas_bokeh.plot_grid([[data_table, p_scatter]], plot_width=400, plot_height=350)
A possible optional keyword parameters that can be passed to bokeh.plotting.figure.scatter is size. Below, we use the sepal length of the Iris data as reference for the size:
#Change one value to clearly see the effect of the size keyword
df.loc[13, "sepal length (cm)"] = 15
#Make scatterplot:
p_scatter = df.plot_bokeh.scatter(
x="petal length (cm)",
y="sepal width (cm)",
category="species",
title="Iris DataSet Visualization with Size Keyword",
size="sepal length (cm)")
In this example you can see, that the additional dimension sepal length cannot be used to clearly differentiate between the virginica and versicolor species.
The barplot API has no special keyword arguments, but accepts optional kwargs of bokeh.plotting.figure.vbar like alpha. It uses per default the index for the bar categories (however, also columns can be used as x-axis category using the x argument).
data = {
'fruits':
['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries'],
'2015': [2, 1, 4, 3, 2, 4],
'2016': [5, 3, 3, 2, 4, 6],
'2017': [3, 2, 4, 4, 5, 3]
}
df = pd.DataFrame(data).set_index("fruits")
p_bar = df.plot_bokeh.bar(
ylabel="Price per Unit [€]",
title="Fruit prices per Year",
alpha=0.6)
Using the stacked keyword argument you also maked stacked barplots:
p_stacked_bar = df.plot_bokeh.bar(
ylabel="Price per Unit [€]",
title="Fruit prices per Year",
stacked=True,
alpha=0.6)
Also horizontal versions of the above barplot are supported with the keyword kind="barh" or the accessor plot_bokeh.barh. You can still specify a column of the DataFrame as the bar category via the x argument if you do not wish to use the index.
#Reset index, such that "fruits" is now a column of the DataFrame:
df.reset_index(inplace=True)
#Create horizontal bar (via kind keyword):
p_hbar = df.plot_bokeh(
kind="barh",
x="fruits",
xlabel="Price per Unit [€]",
title="Fruit prices per Year",
alpha=0.6,
legend = "bottom_right",
show_figure=False)
#Create stacked horizontal bar (via barh accessor):
p_stacked_hbar = df.plot_bokeh.barh(
x="fruits",
stacked=True,
xlabel="Price per Unit [€]",
title="Fruit prices per Year",
alpha=0.6,
legend = "bottom_right",
show_figure=False)
#Plot all barplot examples in a grid:
pandas_bokeh.plot_grid([[p_bar, p_stacked_bar],
[p_hbar, p_stacked_hbar]],
plot_width=450)
For drawing histograms (kind="hist"), Pandas-Bokeh has a lot of customization features. Optional keyword arguments for histogram plots are:
Below examples of the different histogram types:
import numpy as np
df_hist = pd.DataFrame({
'a': np.random.randn(1000) + 1,
'b': np.random.randn(1000),
'c': np.random.randn(1000) - 1
},
columns=['a', 'b', 'c'])
#Top-on-Top Histogram (Default):
df_hist.plot_bokeh.hist(
bins=np.linspace(-5, 5, 41),
vertical_xlabel=True,
hovertool=False,
title="Normal distributions (Top-on-Top)",
line_color="black")
#Side-by-Side Histogram (multiple bars share bin side-by-side) also accessible via
#kind="hist":
df_hist.plot_bokeh(
kind="hist",
bins=np.linspace(-5, 5, 41),
histogram_type="sidebyside",
vertical_xlabel=True,
hovertool=False,
title="Normal distributions (Side-by-Side)",
line_color="black")
#Stacked histogram:
df_hist.plot_bokeh.hist(
bins=np.linspace(-5, 5, 41),
histogram_type="stacked",
vertical_xlabel=True,
hovertool=False,
title="Normal distributions (Stacked)",
line_color="black")
Further, advanced keyword arguments for histograms are:
Their usage is shown in these examples:
p_hist = df_hist.plot_bokeh.hist(
y=["a", "b"],
bins=np.arange(-4, 6.5, 0.5),
normed=100,
vertical_xlabel=True,
ylabel="Share[%]",
title="Normal distributions (normed)",
show_average=True,
xlim=(-4, 6),
ylim=(0, 30),
show_figure=False)
p_hist_cum = df_hist.plot_bokeh.hist(
y=["a", "b"],
bins=np.arange(-4, 6.5, 0.5),
normed=100,
cumulative=True,
vertical_xlabel=True,
ylabel="Share[%]",
title="Normal distributions (normed & cumulative)",
show_figure=False)
pandas_bokeh.plot_grid([[p_hist, p_hist_cum]], plot_width=450, plot_height=300)
Areaplot (kind="area") can be either drawn on top of each other or stacked. The important parameters are:
stacked: If True, the areaplots are stacked. If False, plots are drawn on top of each other. Default: False
kwargs**: Optional keyword arguments of bokeh.plotting.figure.patch
Let us consider the energy consumption split by source that can be downloaded as DataFrame via:
df_energy = pd.read_csv(r"https://raw.githubusercontent.com/PatrikHlobil/Pandas-Bokeh/master/docs/Testdata/energy/energy.csv",
parse_dates=["Year"])
df_energy.head()
Year | Oil | Gas | Coal | Nuclear Energy | Hydroelectricity | Other Renewable |
---|---|---|---|---|---|---|
1970-01-01 | 2291.5 | 826.7 | 1467.3 | 17.7 | 265.8 | 5.8 |
1971-01-01 | 2427.7 | 884.8 | 1459.2 | 24.9 | 276.4 | 6.3 |
1972-01-01 | 2613.9 | 933.7 | 1475.7 | 34.1 | 288.9 | 6.8 |
1973-01-01 | 2818.1 | 978.0 | 1519.6 | 45.9 | 292.5 | 7.3 |
1974-01-01 | 2777.3 | 1001.9 | 1520.9 | 59.6 | 321.1 | 7.7 |
Creating the Areaplot can be achieved via:
df_energy.plot_bokeh.area(
x="Year",
stacked=True,
legend="top_left",
colormap=["brown", "orange", "black", "grey", "blue", "green"],
title="Worldwide energy consumption split by energy source",
ylabel="Million tonnes oil equivalent",
ylim=(0, 16000))
Note that the energy consumption of fossile energy is still increasing and renewable energy sources are still small in comparison 😢!!! However, when we norm the plot using the normed keyword, there is a clear trend towards renewable energies in the last decade:
df_energy.plot_bokeh.area(
x="Year",
stacked=True,
normed=100,
legend="bottom_left",
colormap=["brown", "orange", "black", "grey", "blue", "green"],
title="Worldwide energy consumption split by energy source",
ylabel="Million tonnes oil equivalent")
For Pieplots, let us consider a dataset showing the results of all Bundestags elections in Germany since 2002:
df_pie = pd.read_csv(r"https://raw.githubusercontent.com/PatrikHlobil/Pandas-Bokeh/master/docs/Testdata/Bundestagswahl/Bundestagswahl.csv")
df_pie
Partei | 2002 | 2005 | 2009 | 2013 | 2017 |
---|---|---|---|---|---|
CDU/CSU | 38.5 | 35.2 | 33.8 | 41.5 | 32.9 |
SPD | 38.5 | 34.2 | 23.0 | 25.7 | 20.5 |
FDP | 7.4 | 9.8 | 14.6 | 4.8 | 10.7 |
Grünen | 8.6 | 8.1 | 10.7 | 8.4 | 8.9 |
Linke/PDS | 4.0 | 8.7 | 11.9 | 8.6 | 9.2 |
AfD | 0.0 | 0.0 | 0.0 | 0.0 | 12.6 |
Sonstige | 3.0 | 4.0 | 6.0 | 11.0 | 5.0 |
We can create a Pieplot of the last election in 2017 by specifying the "Partei" (german for party) column as the x column and the "2017" column as the y column for values:
df_pie.plot_bokeh.pie(
x="Partei",
y="2017",
colormap=["blue", "red", "yellow", "green", "purple", "orange", "grey"],
title="Results of German Bundestag Election 2017",
)
When you pass several columns to the y parameter (not providing the y-parameter assumes you plot all columns), multiple nested pieplots will be shown in one plot:
df_pie.plot_bokeh.pie(
x="Partei",
colormap=["blue", "red", "yellow", "green", "purple", "orange", "grey"],
title="Results of German Bundestag Elections [2002-2017]",
line_color="grey")
The mapplot method of Pandas-Bokeh allows for plotting geographic points stored in a Pandas DataFrame on an interactive map. For more advanced Geoplots for line and polygon shapes have a look at the Geoplots examples for the GeoPandas API of Pandas-Bokeh.
For mapplots, only (latitude, longitude) pairs in geographic projection (WGS84) can be plotted on a map. The basic API has the following 2 base parameters:
The other optional keyword arguments are discussed in the section about the GeoPandas API, e.g. category for coloring the points.
Below an example of plotting all cities for more than 1 million inhabitants:
df_mapplot = pd.read_csv(r"https://raw.githubusercontent.com/PatrikHlobil/Pandas-Bokeh/master/docs/Testdata/populated%20places/populated_places.csv")
df_mapplot.head()
name | pop_max | latitude | longitude | size |
---|---|---|---|---|
Mesa | 1085394 | 33.423915 | -111.736084 | 1.085394 |
Sharjah | 1103027 | 25.371383 | 55.406478 | 1.103027 |
Changwon | 1081499 | 35.219102 | 128.583562 | 1.081499 |
Sheffield | 1292900 | 53.366677 | -1.499997 | 1.292900 |
Abbottabad | 1183647 | 34.149503 | 73.199501 | 1.183647 |
df_mapplot["size"] = df_mapplot["pop_max"] / 1000000
df_mapplot.plot_bokeh.map(
x="longitude",
y="latitude",
hovertool_string="""<h2> @{name} </h2>
<h3> Population: @{pop_max} </h3>""",
tile_provider="STAMEN_TERRAIN_RETINA",
size="size",
figsize=(900, 600),
title="World cities with more than 1.000.000 inhabitants")
Pandas-Bokeh also allows for interactive plotting of Maps using GeoPandas by providing a geopandas.GeoDataFrame.plot_bokeh() method. It allows to plot the following geodata on a map :
Note: t is not possible to mix up the objects types, i.e. a GeoDataFrame with Points and Lines is for example not allowed.
Les us start with a simple example using the "World Borders Dataset" . Let us first import all neccessary libraries and read the shapefile:
import geopandas as gpd
import pandas as pd
import pandas_bokeh
pandas_bokeh.output_notebook()
#Read in GeoJSON from URL:
df_states = gpd.read_file(r"https://raw.githubusercontent.com/PatrikHlobil/Pandas-Bokeh/master/docs/Testdata/states/states.geojson")
df_states.head()
STATE_NAME | REGION | POPESTIMATE2010 | POPESTIMATE2011 | POPESTIMATE2012 | POPESTIMATE2013 | POPESTIMATE2014 | POPESTIMATE2015 | POPESTIMATE2016 | POPESTIMATE2017 | geometry |
---|---|---|---|---|---|---|---|---|---|---|
Hawaii | 4 | 1363817 | 1378323 | 1392772 | 1408038 | 1417710 | 1426320 | 1428683 | 1427538 | (POLYGON ((-160.0738033454681 22.0041773479577... |
Washington | 4 | 6741386 | 6819155 | 6890899 | 6963410 | 7046931 | 7152818 | 7280934 | 7405743 | (POLYGON ((-122.4020153103835 48.2252163723779... |
Montana | 4 | 990507 | 996866 | 1003522 | 1011921 | 1019931 | 1028317 | 1038656 | 1050493 | POLYGON ((-111.4754253002074 44.70216236909688... |
Maine | 1 | 1327568 | 1327968 | 1328101 | 1327975 | 1328903 | 1327787 | 1330232 | 1335907 | (POLYGON ((-69.77727626137293 44.0741483685119... |
North Dakota | 2 | 674518 | 684830 | 701380 | 722908 | 738658 | 754859 | 755548 | 755393 | POLYGON ((-98.73043728833767 45.93827137024809... |
Plotting the data on a map is as simple as calling:
df_states.plot_bokeh(simplify_shapes=10000)
We also passed the optional parameter simplify_shapes (~meter) to improve plotting performance (for a reference see shapely.object.simplify). The above geolayer thus has an accuracy of about 10km.
Many keyword arguments like xlabel, ylabel, xlim, ylim, title, colormap, hovertool, zooming, panning, ... for costumizing the plot are also available for the geoplotting API and can be uses as in the examples shown above. There are however also many other options especially for plotting geodata:
One of the most common usage of map plots are choropleth maps, where the color of a the objects is determined by the property of the object itself. There are 3 ways of drawing choropleth maps using Pandas-Bokeh, which are described below.
This is the simplest way. Just provide the category keyword for the selection of the property column:
Let us now draw the regions as a choropleth plot using the category keyword (at the moment, only numerical columns are supported for choropleth plots):
df_states.plot_bokeh(
figsize=(900, 600),
simplify_shapes=5000,
category="REGION",
show_colorbar=False,
colormap=["blue", "yellow", "green", "red"],
hovertool_columns=["STATE_NAME", "REGION"],
tile_provider="STAMEN_TERRAIN_RETINA")
When hovering over the states, the state-name and the region are shown as specified in the hovertool_columns argument.
By passing a list of column names of the GeoDataFrame as the dropdown keyword argument, a dropdown menu is shown above the map. This dropdown menu can be used to select the choropleth layer by the user. :
df_states["STATE_NAME_SMALL"] = df_states["STATE_NAME"].str.lower()
df_states.plot_bokeh(
figsize=(900, 600),
simplify_shapes=5000,
dropdown=["POPESTIMATE2010", "POPESTIMATE2017"],
colormap="Viridis",
hovertool_string="""
<img
src="https://www.states101.com/img/flags/gif/small/@STATE_NAME_SMALL.gif"
height="42" alt="@imgs" width="42"
style="float: left; margin: 0px 15px 15px 0px;"
border="2"></img>
<h2> @STATE_NAME </h2>
<h3> 2010: @POPESTIMATE2010 </h3>
<h3> 2017: @POPESTIMATE2017 </h3>""",
tile_provider_url=r"http://c.tile.stamen.com/watercolor/{Z}/{X}/{Y}.jpg",
tile_attribution='Map tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>. Data by <a href="http://openstreetmap.org">OpenStreetMap</a>, under <a href="http://www.openstreetmap.org/copyright">ODbL</a>.'
)
Using hovertool_string, one can pass a string that can contain arbitrary HTML elements (including divs, images, ...) that is shown when hovering over the geographies (@{column} will be replaced by the value of the column for the element the mouse hovers over, see also Bokeh documentation).
Here, we also used an OSM tile server with watercolor style via tile_provider_url and added the attribution via tile_attribution.
Another option for interactive choropleth maps is the slider implementation of Pandas-Bokeh. The possible keyword arguments are here:
This can be used to display the change in population relative to the year 2010:
#Calculate change of population relative to 2010:
for i in range(8):
df_states["Delta_Population_201%d"%i] = ((df_states["POPESTIMATE201%d"%i] / df_states["POPESTIMATE2010"]) -1 ) * 100
#Specify slider columns:
slider_columns = ["Delta_Population_201%d"%i for i in range(8)]
#Specify slider-range (Maps "Delta_Population_2010" -> 2010,
# "Delta_Population_2011" -> 2011, ...):
slider_range = range(2010, 2018)
#Make slider plot:
df_states.plot_bokeh(
figsize=(900, 600),
simplify_shapes=5000,
slider=slider_columns,
slider_range=slider_range,
slider_name="Year",
colormap="Inferno",
hovertool_columns=["STATE_NAME"] + slider_columns,
title="Change of Population [%]")
If you wish to display multiple geolayers, you can pass the Bokeh figure of a Pandas-Bokeh plot via the figure keyword to the next plot_bokeh() call:
import geopandas as gpd
import pandas_bokeh
pandas_bokeh.output_notebook()
# Read in GeoJSONs from URL:
df_states = gpd.read_file(r"https://raw.githubusercontent.com/PatrikHlobil/Pandas-Bokeh/master/docs/Testdata/states/states.geojson")
df_cities = gpd.read_file(
r"https://raw.githubusercontent.com/PatrikHlobil/Pandas-Bokeh/master/docs/Testdata/populated%20places/ne_10m_populated_places_simple_bigcities.geojson"
)
df_cities["size"] = df_cities.pop_max / 400000
#Plot shapes of US states (pass figure options to this initial plot):
figure = df_states.plot_bokeh(
figsize=(800, 450),
simplify_shapes=10000,
show_figure=False,
xlim=[-170, -80],
ylim=[10, 70],
category="REGION",
colormap="Dark2",
legend="States",
show_colorbar=False,
)
#Plot cities as points on top of the US states layer by passing the figure:
df_cities.plot_bokeh(
figure=figure, # <== pass figure here!
category="pop_max",
colormap="Viridis",
colormap_uselog=True,
size="size",
hovertool_string="""<h1>@name</h1>
<h3>Population: @pop_max </h3>""",
marker="inverted_triangle",
legend="Cities",
)
Below, you can see an example that use Pandas-Bokeh to plot point data on a map. The plot shows all cities with a population larger than 1.000.000. For point plots, you can select the marker as keyword argument (since it is passed to bokeh.plotting.figure.scatter). Here an overview of all available marker types:
gdf = gpd.read_file(r"https://raw.githubusercontent.com/PatrikHlobil/Pandas-Bokeh/master/docs/Testdata/populated%20places/ne_10m_populated_places_simple_bigcities.geojson")
gdf["size"] = gdf.pop_max / 400000
gdf.plot_bokeh(
category="pop_max",
colormap="Viridis",
colormap_uselog=True,
size="size",
hovertool_string="""<h1>@name</h1>
<h3>Population: @pop_max </h3>""",
xlim=[-15, 35],
ylim=[30,60],
marker="inverted_triangle");
In a similar way, also GeoDataFrames with (multi)line shapes can be drawn using Pandas-Bokeh.
If you want to display the numerical labels on your colorbar with an alternative to the scientific format, you can pass in a one of the bokeh number string formats or an instance of one of the bokeh.models.formatters to the colorbar_tick_format
argument in the geoplot
An example of using the string format argument:
df_states = gpd.read_file(r"https://raw.githubusercontent.com/PatrikHlobil/Pandas-Bokeh/master/docs/Testdata/states/states.geojson")
df_states["STATE_NAME_SMALL"] = df_states["STATE_NAME"].str.lower()
# pass in a string format to colorbar_tick_format to display the ticks as 10m rather than 1e7
df_states.plot_bokeh(
figsize=(900, 600),
category="POPESTIMATE2017",
simplify_shapes=5000,
colormap="Inferno",
colormap_uselog=True,
colorbar_tick_format="0.0a")
An example of using the bokeh PrintfTickFormatter
:
df_states = gpd.read_file(r"https://raw.githubusercontent.com/PatrikHlobil/Pandas-Bokeh/master/docs/Testdata/states/states.geojson")
df_states["STATE_NAME_SMALL"] = df_states["STATE_NAME"].str.lower()
for i in range(8):
df_states["Delta_Population_201%d"%i] = ((df_states["POPESTIMATE201%d"%i] / df_states["POPESTIMATE2010"]) -1 ) * 100
# pass in a PrintfTickFormatter instance colorbar_tick_format to display the ticks with 2 decimal places
df_states.plot_bokeh(
figsize=(900, 600),
category="Delta_Population_2017",
simplify_shapes=5000,
colormap="Inferno",
colorbar_tick_format=PrintfTickFormatter(format="%4.2f"))
The pandas.DataFrame.plot_bokeh API has the following additional keyword arguments:
If you have a Bokeh figure or layout, you can also use the pandas_bokeh.embedded_html function to generate an embeddable HTML representation of the plot. This can be included into any valid HTML (note that this is not possible directly with the HTML generated by the pandas_bokeh.output_file output option, because it includes an HTML header). Let us consider the following simple example:
#Import Pandas and Pandas-Bokeh (if you do not specify an output option, the standard is
#output_file):
import pandas as pd
import pandas_bokeh
#Create DataFrame to Plot:
import numpy as np
x = np.arange(-10, 10, 0.1)
sin = np.sin(x)
cos = np.cos(x)
tan = np.tan(x)
df = pd.DataFrame({"x": x, "sin(x)": sin, "cos(x)": cos, "tan(x)": tan})
#Make Bokeh plot from DataFrame using Pandas-Bokeh. Do not show the plot, but export
#it to an embeddable HTML string:
html_plot = df.plot_bokeh(
kind="line",
x="x",
y=["sin(x)", "cos(x)", "tan(x)"],
xticks=range(-20, 20),
title="Trigonometric functions",
show_figure=False,
return_html=True,
ylim=(-1.5, 1.5))
#Write some HTML and embed the HTML plot below it. For production use, please use
#Templates and the awesome Jinja library.
html = r"""
<script type="text/x-mathjax-config">
MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}});
</script>
<script type="text/javascript"
src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<h1> Trigonometric functions </h1>
<p> The basic trigonometric functions are:</p>
<p>$ sin(x) $</p>
<p>$ cos(x) $</p>
<p>$ tan(x) = \frac{sin(x)}{cos(x)}$</p>
<p>Below is a plot that shows them</p>
""" + html_plot
#Export the HTML string to an external HTML file and show it:
with open("test.html" , "w") as f:
f.write(html)
import webbrowser
webbrowser.open("test.html")
This code will open up a webbrowser and show the following page. As you can see, the interactive Bokeh plot is embedded nicely into the HTML layout. The return_html option is ideal for the use in a templating engine like Jinja.
For single plots that have a number of x axis values or for larger monitors, you can auto scale the figure to the width of the entire jupyter cell by setting the sizing_mode
parameter.
df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
df.plot_bokeh(kind="bar", figsize=(500, 200), sizing_mode="scale_width")
The figsize
parameter can be used to change the height and width as well as act as a scaling multiplier against the axis that is not being scaled.
To change the formats of numbers in the hovertool, use the number_format keyword argument. For a documentation about the format to pass, have a look at the Bokeh documentation.Let us consider some examples for the number 3.141592653589793:
Format | Output |
---|---|
0 | 3 |
0.000 | 3.141 |
0.00 $ | 3.14 $ |
This number format will be applied to all numeric columns of the hovertool. If you want to make a very custom or complicated hovertool, you should probably use the hovertool_string keyword argument, see e.g. this example. Below, we use the number_format parameter to specify the "Stock Price" format to 2 decimal digits and an additional $ sign.
import numpy as np
#Lineplot:
np.random.seed(42)
df = pd.DataFrame({
"Google": np.random.randn(1000) + 0.2,
"Apple": np.random.randn(1000) + 0.17
},
index=pd.date_range('1/1/2000', periods=1000))
df = df.cumsum()
df = df + 50
df.plot_bokeh(
kind="line",
title="Apple vs Google",
xlabel="Date",
ylabel="Stock price [$]",
yticks=[0, 100, 200, 300, 400],
ylim=(0, 400),
colormap=["red", "blue"],
number_format="1.00 $")
If you want to suppress the scientific notation for axes, you can use the disable_scientific_axes parameter, which accepts one of "x", "y", "xy":
df = pd.DataFrame({"Animal": ["Mouse", "Rabbit", "Dog", "Tiger", "Elefant", "Wale"],
"Weight [g]": [19, 3000, 40000, 200000, 6000000, 50000000]})
p_scientific = df.plot_bokeh(x="Animal", y="Weight [g]", show_figure=False)
p_non_scientific = df.plot_bokeh(x="Animal", y="Weight [g]", disable_scientific_axes="y", show_figure=False,)
pandas_bokeh.plot_grid([[p_scientific, p_non_scientific]], plot_width = 450)
As shown in the Scatterplot Example, combining plots with plots or other HTML elements is straighforward in Pandas-Bokeh due to the layout capabilities of Bokeh. The easiest way to generate a dashboard layout is using the pandas_bokeh.plot_grid method (which is an extension of bokeh.layouts.gridplot):
import pandas as pd
import numpy as np
import pandas_bokeh
pandas_bokeh.output_notebook()
#Barplot:
data = {
'fruits':
['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries'],
'2015': [2, 1, 4, 3, 2, 4],
'2016': [5, 3, 3, 2, 4, 6],
'2017': [3, 2, 4, 4, 5, 3]
}
df = pd.DataFrame(data).set_index("fruits")
p_bar = df.plot_bokeh(
kind="bar",
ylabel="Price per Unit [€]",
title="Fruit prices per Year",
show_figure=False)
#Lineplot:
np.random.seed(42)
df = pd.DataFrame({
"Google": np.random.randn(1000) + 0.2,
"Apple": np.random.randn(1000) + 0.17
},
index=pd.date_range('1/1/2000', periods=1000))
df = df.cumsum()
df = df + 50
p_line = df.plot_bokeh(
kind="line",
title="Apple vs Google",
xlabel="Date",
ylabel="Stock price [$]",
yticks=[0, 100, 200, 300, 400],
ylim=(0, 400),
colormap=["red", "blue"],
show_figure=False)
#Scatterplot:
from sklearn.datasets import load_iris
iris = load_iris()
df = pd.DataFrame(iris["data"])
df.columns = iris["feature_names"]
df["species"] = iris["target"]
df["species"] = df["species"].map(dict(zip(range(3), iris["target_names"])))
p_scatter = df.plot_bokeh(
kind="scatter",
x="petal length (cm)",
y="sepal width (cm)",
category="species",
title="Iris DataSet Visualization",
show_figure=False)
#Histogram:
df_hist = pd.DataFrame({
'a': np.random.randn(1000) + 1,
'b': np.random.randn(1000),
'c': np.random.randn(1000) - 1
},
columns=['a', 'b', 'c'])
p_hist = df_hist.plot_bokeh(
kind="hist",
bins=np.arange(-6, 6.5, 0.5),
vertical_xlabel=True,
normed=100,
hovertool=False,
title="Normal distributions",
show_figure=False)
#Make Dashboard with Grid Layout:
pandas_bokeh.plot_grid([[p_line, p_bar],
[p_scatter, p_hist]], plot_width=450)
Using a combination of row and column elements (see also Bokeh Layouts) allow for a very easy general arrangement of elements. An alternative layout to the one above is:
p_line.plot_width = 900
p_hist.plot_width = 900
layout = pandas_bokeh.column(p_line,
pandas_bokeh.row(p_scatter, p_bar),
p_hist)
pandas_bokeh.show(layout)
Release Notes can be found here.
Contributing to Pandas-Bokeh
If you wish to contribute to the development of Pandas-Bokeh
you can follow the instructions on the CONTRIBUTING.md.
Download Details:
Author: PatrikHlobil
Source Code: https://github.com/PatrikHlobil/Pandas-Bokeh
License: MIT License
1561523460
This Matplotlib cheat sheet introduces you to the basics that you need to plot your data with Python and includes code samples.
Data visualization and storytelling with your data are essential skills that every data scientist needs to communicate insights gained from analyses effectively to any audience out there.
For most beginners, the first package that they use to get in touch with data visualization and storytelling is, naturally, Matplotlib: it is a Python 2D plotting library that enables users to make publication-quality figures. But, what might be even more convincing is the fact that other packages, such as Pandas, intend to build more plotting integration with Matplotlib as time goes on.
However, what might slow down beginners is the fact that this package is pretty extensive. There is so much that you can do with it and it might be hard to still keep a structure when you're learning how to work with Matplotlib.
DataCamp has created a Matplotlib cheat sheet for those who might already know how to use the package to their advantage to make beautiful plots in Python, but that still want to keep a one-page reference handy. Of course, for those who don't know how to work with Matplotlib, this might be the extra push be convinced and to finally get started with data visualization in Python.
You'll see that this cheat sheet presents you with the six basic steps that you can go through to make beautiful plots.
Check out the infographic by clicking on the button below:
With this handy reference, you'll familiarize yourself in no time with the basics of Matplotlib: you'll learn how you can prepare your data, create a new plot, use some basic plotting routines to your advantage, add customizations to your plots, and save, show and close the plots that you make.
What might have looked difficult before will definitely be more clear once you start using this cheat sheet! Use it in combination with the Matplotlib Gallery, the documentation.
Matplotlib
Matplotlib is a Python 2D plotting library which produces publication-quality figures in a variety of hardcopy formats and interactive environments across platforms.
>>> import numpy as np
>>> x = np.linspace(0, 10, 100)
>>> y = np.cos(x)
>>> z = np.sin(x)
>>> data = 2 * np.random.random((10, 10))
>>> data2 = 3 * np.random.random((10, 10))
>>> Y, X = np.mgrid[-3:3:100j, -3:3:100j]
>>> U = 1 X** 2 + Y
>>> V = 1 + X Y**2
>>> from matplotlib.cbook import get_sample_data
>>> img = np.load(get_sample_data('axes_grid/bivariate_normal.npy'))
>>> import matplotlib.pyplot as plt
>>> fig = plt.figure()
>>> fig2 = plt.figure(figsize=plt.figaspect(2.0))
>>> fig.add_axes()
>>> ax1 = fig.add_subplot(221) #row-col-num
>>> ax3 = fig.add_subplot(212)
>>> fig3, axes = plt.subplots(nrows=2,ncols=2)
>>> fig4, axes2 = plt.subplots(ncols=3)
>>> plt.savefig('foo.png') #Save figures
>>> plt.savefig('foo.png', transparent=True) #Save transparent figures
>>> plt.show()
>>> fig, ax = plt.subplots()
>>> lines = ax.plot(x,y) #Draw points with lines or markers connecting them
>>> ax.scatter(x,y) #Draw unconnected points, scaled or colored
>>> axes[0,0].bar([1,2,3],[3,4,5]) #Plot vertical rectangles (constant width)
>>> axes[1,0].barh([0.5,1,2.5],[0,1,2]) #Plot horiontal rectangles (constant height)
>>> axes[1,1].axhline(0.45) #Draw a horizontal line across axes
>>> axes[0,1].axvline(0.65) #Draw a vertical line across axes
>>> ax.fill(x,y,color='blue') #Draw filled polygons
>>> ax.fill_between(x,y,color='yellow') #Fill between y values and 0
>>> fig, ax = plt.subplots()
>>> im = ax.imshow(img, #Colormapped or RGB arrays
cmap= 'gist_earth',
interpolation= 'nearest',
vmin=-2,
vmax=2)
>>> axes2[0].pcolor(data2) #Pseudocolor plot of 2D array
>>> axes2[0].pcolormesh(data) #Pseudocolor plot of 2D array
>>> CS = plt.contour(Y,X,U) #Plot contours
>>> axes2[2].contourf(data1) #Plot filled contours
>>> axes2[2]= ax.clabel(CS) #Label a contour plot
>>> axes[0,1].arrow(0,0,0.5,0.5) #Add an arrow to the axes
>>> axes[1,1].quiver(y,z) #Plot a 2D field of arrows
>>> axes[0,1].streamplot(X,Y,U,V) #Plot a 2D field of arrows
>>> ax1.hist(y) #Plot a histogram
>>> ax3.boxplot(y) #Make a box and whisker plot
>>> ax3.violinplot(z) #Make a violin plot
y-axis
x-axis
The basic steps to creating plots with matplotlib are:
1 Prepare Data
2 Create Plot
3 Plot
4 Customized Plot
5 Save Plot
6 Show Plot
>>> import matplotlib.pyplot as plt
>>> x = [1,2,3,4] #Step 1
>>> y = [10,20,25,30]
>>> fig = plt.figure() #Step 2
>>> ax = fig.add_subplot(111) #Step 3
>>> ax.plot(x, y, color= 'lightblue', linewidth=3) #Step 3, 4
>>> ax.scatter([2,4,6],
[5,15,25],
color= 'darkgreen',
marker= '^' )
>>> ax.set_xlim(1, 6.5)
>>> plt.savefig('foo.png' ) #Step 5
>>> plt.show() #Step 6
>>> plt.cla() #Clear an axis
>>> plt.clf(). #Clear the entire figure
>>> plt.close(). #Close a window
>>> plt.plot(x, x, x, x**2, x, x** 3)
>>> ax.plot(x, y, alpha = 0.4)
>>> ax.plot(x, y, c= 'k')
>>> fig.colorbar(im, orientation= 'horizontal')
>>> im = ax.imshow(img,
cmap= 'seismic' )
>>> fig, ax = plt.subplots()
>>> ax.scatter(x,y,marker= ".")
>>> ax.plot(x,y,marker= "o")
>>> plt.plot(x,y,linewidth=4.0)
>>> plt.plot(x,y,ls= 'solid')
>>> plt.plot(x,y,ls= '--')
>>> plt.plot(x,y,'--' ,x**2,y**2,'-.' )
>>> plt.setp(lines,color= 'r',linewidth=4.0)
>>> ax.text(1,
-2.1,
'Example Graph',
style= 'italic' )
>>> ax.annotate("Sine",
xy=(8, 0),
xycoords= 'data',
xytext=(10.5, 0),
textcoords= 'data',
arrowprops=dict(arrowstyle= "->",
connectionstyle="arc3"),)
>>> plt.title(r '$sigma_i=15$', fontsize=20)
Limits & Autoscaling
>>> ax.margins(x=0.0,y=0.1) #Add padding to a plot
>>> ax.axis('equal') #Set the aspect ratio of the plot to 1
>>> ax.set(xlim=[0,10.5],ylim=[-1.5,1.5]) #Set limits for x-and y-axis
>>> ax.set_xlim(0,10.5) #Set limits for x-axis
Legends
>>> ax.set(title= 'An Example Axes', #Set a title and x-and y-axis labels
ylabel= 'Y-Axis',
xlabel= 'X-Axis')
>>> ax.legend(loc= 'best') #No overlapping plot elements
Ticks
>>> ax.xaxis.set(ticks=range(1,5), #Manually set x-ticks
ticklabels=[3,100, 12,"foo" ])
>>> ax.tick_params(axis= 'y', #Make y-ticks longer and go in and out
direction= 'inout',
length=10)
Subplot Spacing
>>> fig3.subplots_adjust(wspace=0.5, #Adjust the spacing between subplots
hspace=0.3,
left=0.125,
right=0.9,
top=0.9,
bottom=0.1)
>>> fig.tight_layout() #Fit subplot(s) in to the figure area
Axis Spines
>>> ax1.spines[ 'top'].set_visible(False) #Make the top axis line for a plot invisible
>>> ax1.spines['bottom' ].set_position(( 'outward',10)) #Move the bottom axis line outward
Have this Cheat Sheet at your fingertips
Original article source at https://www.datacamp.com
#matplotlib #cheatsheet #python