0

I am trying to make web-based snake&ladder game on Django, for which I am using matplotlib and mpld3 to create and display my game data on web page.

I am able to get my image on the web page but it is inverted.

Where am I going wrong in this code?

my views.py file:

import matplotlib.image as mpimg
import mpld3 as mpld3
import numpy as np
import matplotlib.pyplot as plt

def home(request):
    image =  mpimg.imread('platform3.png')
    figure = plt.figure(dpi=100)
    subplot = figure.add_subplot(111)
    subplot.set_xlim(0, 10)
    subplot.set_ylim(0, 10)
    subplot.imshow(image, extent=[0, 10, 0, 10])
    canvas = FigureCanvas(figure)
    response = django.http.HttpResponse(content_type='image/png')
    canvas.print_png(response)
    html_gen = 'graph.html'
    with open(html_gen, 'w') as f:
        f.write(mpld3.fig_to_html(figure))
        f.write("Hello")

    return render(request, html_gen)

should I provide the generated html_gen.html file too?

Shubham Namdeo
  • 1,845
  • 2
  • 24
  • 40

1 Answers1

1

Just place the [0, 0] in the lower left corner of the axes with:

subplot.imshow(image, extent=[0, 10, 0, 10], origin='lower')

Please have a look at the imshow() docs

Update: How to check and set a default image.origin value

  1. Check:

    >>> import matplotlib as mpl
    >>> print(mpl.rcParams['image.origin'])
    upper
    
  2. Set lower as a default value (docs):

    $ echo "image.origin : lower" >> .config/matplotlib/matplotlibrc
    
  3. Check again:

    >>> import matplotlib as mpl
    >>> print(mpl.rcParams['image.origin'])
    upper
    
twil
  • 6,032
  • 1
  • 30
  • 28
  • This worked for me, but I have one question here, when I haven't mentioned origin, as default it took None right. So why does it got my image inverted? does it take some other value as origin? – Shubham Namdeo Dec 07 '16 at 01:42
  • By default (I'm using default packages from Ubuntu 16.04) `image.origin = 'upper'`. I've updated the answer with more info on a subject. – twil Dec 07 '16 at 02:17
  • Thank you for this detailed explanation. I got it now. I am also using ubuntu 16.04 and used set lower as default as you mentioned. – Shubham Namdeo Dec 07 '16 at 02:23