question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Setting Custom Domain on datetime Axis

See original GitHub issue

I’m trying to set the domain on my x-axis for a time based line/area chart. I’ve tried a few different things based on other issues raised here- but this is my closest result:

y = list(range(0,100))
x = [datetime.datetime(2017, 1, 1) + datetime.timedelta(days=i) for i in y]

# What I wanted to do
# domain = [datetime.datetime(2017,1,5), datetime.datetime(2017,1,30)]
# Per https://github.com/altair-viz/altair/issues/558
# domain_seconds = [(x - datetime.datetime(1970,1,1)).total_seconds() for x in domain]
# Per comment: https://github.com/altair-viz/altair/issues/187#issuecomment-244126070
domain_pd = pd.to_datetime(['2016-12-15', '2017-01-15']).astype(int) / 10 ** 6

time_data = pd.DataFrame({
    'x': x,
    'y': y
})

alt.Chart(time_data).mark_line().encode(
    alt.X('x:T', timeUnit='yearmonthdate', scale=alt.Scale(domain=list(domain_pd))),
    alt.Y('y:Q')
).properties(
    title='Example chart'
)

image

As you can see, this didn’t exactly work out. What I really want to do is pass in dates in the domain field and have the chart start and end on those dates. This should happen regardless of the presence of data. For my application there may or may not be data in the dates given. Am I passing in these dates in the right place?

FYI I’m running altair 2.1.0 in a jupyter notebook.

I’m tracking the following issues to try and resolve this:

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:14 (7 by maintainers)

github_iconTop GitHub Comments

3reactions
jakevdpcommented, Jul 7, 2018

Just thinking out loud… sorry for the multiple posts.

Maybe the best way to do this would be to make alt.DateTime accept a flexible range of inputs, so that the user could do

alt.Scale(domain=[alt.DateTime('2016-12-15'), alt.DateTime('2017-01-15')])

That seems concise and convenient, and also nice and explicit.

Edit: This would involve adding the following class to altair/vegalite/v2/api/py:

import altair as alt
import pandas as pd

class DateTime(alt.DateTime):
    @staticmethod
    def _shorthand_to_dict(shorthand):
        dt = pd.to_datetime(shorthand)
        return dict(year=dt.year, month=dt.month, date=dt.day,
                    hours=dt.hour, minutes=dt.minute, seconds=dt.second,
                    milliseconds=0.001 * dt.microsecond)
    
    def __init__(self, shorthand=alt.Undefined, **kwargs):
        if shorthand is not alt.Undefined:
            # TODO: warn if this involves overwriting
            kwargs.update(self._shorthand_to_dict(shorthand))
        super(alt.DateTime, self).__init__(**kwargs)
1reaction
SyntaxRulescommented, Jul 9, 2018

Nice to see vega-lite will be making this a little easier. If I understand right after vega-lite incorporates this into a release (is this in 2.6.0?) altair can handle:

domain=['2016-12-15', '2017-01-15']
# or
domain=[datetime.date(2016, 12, 15).isoformat(), datetime.date(2017, 1, 15).isoformat()]

I’m looking forward to trying this out.

Read more comments on GitHub >

github_iconTop Results From Across the Web

how to set proper domain for date time scale in d3
Am using "d3.time.scale" on x-axis. The problem is scale and ticks start on x-axis right from origin and because of this i get...
Read more >
Customizing date formats in Amazon QuickSight
Example Description Token 99 or 21 A 2‑digit representation of a year. YY 1999 or 2021 A full, 4‑digit numeric representation of a year. YYYY 1–12...
Read more >
Custom Axis Tick Formatters Axes Example | charts - Google
Example of timeseries chart with custom measure and domain formatters. import ... animate: animate, // Sets up a currency formatter for the measure...
Read more >
Python: Altair - Setting the range of Date values for an axis
Learn how to set the range of date values on the x axis of an Altair chart. ... and then define a custom...
Read more >
Python Figure Reference: layout.xaxis - Plotly
( domain)?$/" ). If set to an opposite-letter axis id (e.g. `x2`, `y`), ... If this axis needs to be compressed (either due...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found