haskell-chart icon indicating copy to clipboard operation
haskell-chart copied to clipboard

how to render purely?

Open jwaldmann opened this issue 7 years ago • 1 comments

I am unable to figure out how to transform a chart to SVG in a pure way. I thought that's one of the main reasons for having these native back-ends?

It seems the roadblock is defaultEnv which is in IO. Why is this? It tries to determine something about fonts - by reading something from disk. But what's the use if the resulting SVG document will be rendered elsewhere?

Here is my best attempt at understanding the rendering process. All of this is pure, except for defaultEnv (that's the point of this issue) and putStrLn (which is not the point, since it's just for testing)

{-# language OverloadedStrings #-}

import Graphics.Rendering.Chart.Easy
import Diagrams.Backend.SVG
import Diagrams.Core.Compile
import Diagrams.Core.Types (QDiagram)
import Data.Monoid (Any)
import Diagrams.TwoD.Types (V2)
import Diagrams.TwoD (mkWidth)
import Diagrams.Core.V (N)
import Graphics.Rendering.Chart.Backend.Diagrams
import Graphics.Svg.Core (renderBS)
import qualified Data.ByteString.Lazy as BS

main = do
  let r :: Renderable ()
      r = toRenderable $ plot
        $ line "sin" [ [ (x , sin x) | x <- [ 0 :: Double, 0.1 .. 10 ] ] ]

  de <- defaultEnv (AlignmentFns id id) 100 100
  
  let b :: BackendProgram (PickFn ())
      b = render r (100,100)
  let (q, _) = runBackend de b :: (QDiagram SVG V2 (N SVG) Any, PickFn ())
  let opts = (SVGOptions (mkWidth 250) Nothing "" [] True)
  let res :: BS.ByteString
      res = renderBS $ renderDia Diagrams.Backend.SVG.SVG opts q

  BS.putStrLn res

jwaldmann avatar Nov 04 '18 15:11 jwaldmann

You are correct. In standard usage, Chart rendering with the diagrams backend is pure except for the loading of the fonts (see loadFont in the the SVG fonts library http://hackage.haskell.org/package/SVGFonts-1.7/docs/Graphics-SVGFonts.html).

Your application doesn't have to follow this pattern however. You could arrange for the fonts of interest to you to be embedded in your code, and rather than calling defaultEnv construct the DEnv context directly.

timbod7 avatar Nov 04 '18 20:11 timbod7